- Google Drive OAuth for Payload CMS: Complete Guide
Google Drive OAuth for Payload CMS: Complete Guide
Step-by-step setup for multi-tenant Google Drive OAuth in Payload CMS — token persistence, tenant-aware storage, and…

Moving to Next.js and Payload CMS? I offer advisory support on an hourly basis.
Book Hourly AdvisoryI was wiring Google Drive into a multi-tenant Payload CMS app and expected OAuth to be the easy part. The Google consent screen worked quickly, but callback persistence failed on tenant/user constraints and then failed again on migration collisions. This guide is the exact implementation that ended up working in production-style conditions, including the fixes for the errors you are most likely to hit.
By the end, you will have a working Google Drive OAuth flow in Payload CMS with:
Start in Google Cloud Console with a dedicated project (for example, aArheko) and enable Google Drive API.
Then create OAuth client ID (Web application) and define both JavaScript origins and redirect URIs.
For your setup, this is valid and complete:
https://www.arheko.euhttp://localhost:3000https://23e7-46-124-201-0.ngrok-free.apphttps://www.arheko.eu/api/integrations/google/callbackhttps://arheko.eu/api/integrations/google/callbackhttp://localhost:3000/api/integrations/google/callbackhttps://23e7-46-124-201-0.ngrok-free.app/api/integrations/google/callbackThe critical rule is exact matching. If callback URL differs by domain, scheme, or path, token exchange fails.
On scopes, keep this minimal unless you have a hard requirement for broader access. For this integration, these scopes are enough:
openidemailprofilehttps://www.googleapis.com/auth/drive.filehttps://www.googleapis.com/auth/drive.metadata.readonlyIf you add broad scopes like drive or docs, you increase review and consent complexity without helping basic integration setup.
Create/update your env file with OAuth credentials.
# .env.local
GOOGLE_OAUTH_CLIENT_ID=your_client_id.apps.googleusercontent.com
GOOGLE_OAUTH_CLIENT_SECRET=your_client_secret
GOOGLE_OAUTH_REDIRECT_URI=http://localhost:3000/api/integrations/google/callback
# Optional (recommended for production):
GOOGLE_OAUTH_TOKEN_ENCRYPTION_KEY=replace_with_strong_secret
GOOGLE_OAUTH_REDIRECT_URI is optional in this implementation because fallback logic derives it from server URL/origin, but explicit is better for predictability.
Install the official Node SDK used by the server routes.
pnpm add googleapis
Create a dedicated collection to store provider metadata, user/tenant mapping, and tokens.
// File: src/payload/collections/configuration/google-connections/index.ts
import type { CollectionConfig } from 'payload';
export const GoogleConnections: CollectionConfig = {
slug: 'google-connections',
indexes: [
{
fields: ['provider', 'activeTenantId', 'payloadUserId', 'googleAccountEmail'],
unique: true,
},
],
fields: [
{ name: 'provider', type: 'select', required: true, defaultValue: 'google-drive', options: [{ label: 'Google Drive', value: 'google-drive' }] },
{ name: 'tenant', type: 'relationship', relationTo: 'tenants' },
{ name: 'user', type: 'relationship', relationTo: 'users' },
{ name: 'payloadUserId', type: 'number', required: true, index: true },
{ name: 'activeTenantId', type: 'number', required: true, index: true },
{ name: 'googleAccountEmail', type: 'email', required: true, index: true },
{ name: 'googleAccountId', type: 'text' },
{
name: 'scopes',
type: 'array',
fields: [{ name: 'value', type: 'text', required: true }],
},
{ name: 'accessToken', type: 'textarea', access: { read: () => false } },
{ name: 'refreshToken', type: 'textarea', access: { read: () => false } },
{ name: 'tokenType', type: 'text' },
{ name: 'expiryDate', type: 'date' },
{ name: 'isActive', type: 'checkbox', required: true, defaultValue: true, index: true },
{ name: 'lastSyncedAt', type: 'date' },
{ name: 'lastError', type: 'textarea' },
],
};
This structure gives you two important things. First, relation fields (tenant, user) for admin readability. Second, stable numeric ownership keys (activeTenantId, payloadUserId) for route filtering without relation validation surprises in multi-tenant flows.
Then register this collection in:
src/payload/collections/index.tspayload.config.tssrc/payload/access-control/visibility.tsCreate a helper that centralizes OAuth client creation and token encryption.
// File: src/lib/google/oauth.ts
import crypto from 'node:crypto';
import { google } from 'googleapis';
export const GOOGLE_DRIVE_SCOPES = [
'openid',
'email',
'profile',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata.readonly',
] as const;
export function getGoogleOAuthEnv(origin?: string) {
const clientId = (process.env.GOOGLE_OAUTH_CLIENT_ID || '').trim();
const clientSecret = (process.env.GOOGLE_OAUTH_CLIENT_SECRET || '').trim();
const configuredRedirectUri = (process.env.GOOGLE_OAUTH_REDIRECT_URI || '').trim();
const base = (process.env.NEXT_PUBLIC_SERVER_URL || origin || '').replace(/\/$/, '');
const redirectUri = configuredRedirectUri || `${base}/api/integrations/google/callback`;
if (!clientId || !clientSecret || !redirectUri) {
throw new Error('Missing Google OAuth env configuration');
}
return { clientId, clientSecret, redirectUri };
}
export function createGoogleOAuthClient(env: { clientId: string; clientSecret: string; redirectUri: string }) {
return new google.auth.OAuth2(env.clientId, env.clientSecret, env.redirectUri);
}
The key benefit here is route simplicity. Each route imports the same logic for env parsing and OAuth client creation, so behavior is consistent between local, ngrok, and production.
You need four routes.
// File: src/app/api/integrations/google/start/route.ts
const authorizationUrl = client.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: [...GOOGLE_DRIVE_SCOPES],
state,
include_granted_scopes: true,
});
return NextResponse.redirect(authorizationUrl);
This route authenticates the current user, resolves active tenant, stores short-lived cookies (state, tenant, returnTo), then redirects to Google.
// File: src/app/api/integrations/google/callback/route.ts
const tokenResponse = await client.getToken(code);
client.setCredentials(tokenResponse.tokens);
const profile = await fetchGoogleProfile(client);
const connectionData = {
provider: 'google-drive' as const,
user: user.id,
tenant: tenantId,
payloadUserId: user.id,
activeTenantId: tenantId,
googleAccountEmail: profile.email,
accessToken: encryptToken(tokens.access_token || null),
refreshToken: encryptToken(nextRefreshToken),
tokenType: tokens.token_type || null,
expiryDate: tokens.expiry_date ? new Date(tokens.expiry_date).toISOString() : null,
isActive: true,
};
This is the most important step. It validates state, exchanges the code, and persists the connection. In this implementation we intentionally write both relation and numeric ownership fields because that proved most stable with existing schema constraints.
GET /api/integrations/google/status returns a safe payload (connected, email, scopes, expiry, updatedAt) without exposing tokens.
POST /api/integrations/google/disconnect attempts token revoke and then marks connection inactive while clearing stored tokens.
Add an Integrations section under your admin settings and a nested Google page.
// File: src/app/admin/settings/integrations/google/page.tsx
<Button asChild>
<Link href="/api/integrations/google/start?returnTo=/admin/settings/integrations/google">
{isConnected ? 'Reconnect Google Drive' : 'Connect Google Drive'}
</Link>
</Button>
{isConnected ? (
<form method="post" action="/api/integrations/google/disconnect">
<Button type="submit" variant="outline">Disconnect</Button>
</form>
) : null}
The page also reads current connection from Payload and renders account/scopes/expiry so users can see the actual integration state.
Run the standard Payload flow:
pnpm payload generate:types pnpm payload migrate
If your project script uses cross-env and that package is not present, invoke Payload CLI directly as shown above.
This setup hit three real issues during implementation.
First, callback failed with ValidationError: User is invalid. The fix was to introduce payloadUserId and activeTenantId and use those for ownership filters, while still writing relation fields for compatibility.
Second, migration failed because custom tenantId / userId names collided with relation-backed tenant_id / user_id database columns. Renaming to activeTenantId / payloadUserId removed the collision.
Third, callback insert failed because google_connections.user_id was NOT NULL in the existing schema and insert attempted default/null. Explicitly writing user: user.id fixed that insert path immediately.
If you see callback errors with SQL details, decode the details= query param in your redirected URL. It usually reveals the exact column/constraint mismatch in seconds.
GOOGLE_OAUTH_CLIENT_ID, GOOGLE_OAUTH_CLIENT_SECRET, redirect URI).googleapis installed.google-connections collection registered./admin/settings/integrations/google.At this point, your OAuth foundation is complete and you can build actual Drive operations (file listing, upload, sync) on top of a stable connection model.
Let me know in the comments if you have questions, and subscribe for more practical development guides.
Thanks, Matija
Detailed Payload guides with field configuration examples, custom components, and workflow optimization tips to speed up your CMS development process.