← Docs

Add Gmail OAuth to a Next.js App

Use inbox.dog to add Gmail authentication to your Next.js app with App Router. Two API routes and one button component.

Prerequisites

  • A Next.js app with App Router (Next.js 13+)
  • An inbox.dog API key (get one here if you don't have one)

Add environment variables

Create or update your .env.local file:

INBOX_DOG_CLIENT_ID=your_client_id
INBOX_DOG_CLIENT_SECRET=your_client_secret

Create the auth route

Create app/api/auth/gmail/route.ts:

import { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const clientId = process.env.INBOX_DOG_CLIENT_ID;
  const redirectUri = `${request.nextUrl.origin}/api/auth/gmail/callback`;

  const authUrl = new URL('https://inbox.dog/oauth/authorize');
  authUrl.searchParams.set('client_id', clientId!);
  authUrl.searchParams.set('redirect_uri', redirectUri);
  authUrl.searchParams.set('scope', 'email');

  return Response.redirect(authUrl.toString());
}

Create the callback route

Create app/api/auth/gmail/callback/route.ts:

import { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const code = request.nextUrl.searchParams.get('code');

  if (!code) {
    return Response.redirect(new URL('/?error=no_code', request.url));
  }

  const response = await fetch('https://inbox.dog/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      code,
      client_id: process.env.INBOX_DOG_CLIENT_ID,
      client_secret: process.env.INBOX_DOG_CLIENT_SECRET,
    }),
  });

  const data = await response.json();

  if (!response.ok) {
    console.error('Token exchange failed:', data);
    return Response.redirect(new URL('/?error=token_exchange', request.url));
  }

  // Store tokens in your database or session here
  // data contains: { email, access_token, refresh_token, expires_in }

  // For now, redirect to a success page with the email
  return Response.redirect(
    new URL(`/?success=true&email=${encodeURIComponent(data.email)}`, request.url)
  );
}

Add the "Connect Gmail" button

In any client component:

'use client';

export function ConnectGmailButton() {
  return (
    <a
      href="/api/auth/gmail"
      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
    >
      Connect Gmail
    </a>
  );
}

How it works

  1. User clicks the button, which navigates to /api/auth/gmail
  2. The route redirects to inbox.dog with your client_id and a callback URL
  3. inbox.dog handles the Google OAuth flow
  4. User is redirected back to /api/auth/gmail/callback with a code
  5. Your callback route exchanges the code for tokens by calling inbox.dog/oauth/token
  6. Store the tokens in your database or session, then redirect the user

Next steps