Published on

NextAuth.js behinds a proxy

7 minutes read - ––– views
Authors

Overview

In this tutorial, we'll build the following two-part setup:

  1. A Next.js app using next-auth deployed on Vercel.
  2. A main Next.js app deployed on Netlify. We route the subpath /authjs to the secondary app.

TL;DR: Here are the repositories and the live example: The main app and its repository & the next-auth app and its repository.

Prerequisites

A GitHub account. Learn how to create a GitHub account at https://github.com/signup

Step-by-step guide

We’ll have the following steps to follow:

  1. Configure Netlify redirect rule for the main app & deploy it to Netlify.
  2. Configure the next-auth app with custom Next.js configurations to work when deployed under a subpath.
  3. Configure next-auth to work with this Next.js configuration.
  4. Configure the GitHub OAuth provider.
  5. Deploy the next-auth app to Vercel.

Let’s dive right in.

Configure Netlify redirect rule & deploy the main app

For this example, let's use the most basic Next.js app created from create-next-app.

npx create-next-app my-app
cd my-app
npm run dev

Add a link to /authjs in the landing page by editing the pages/index.ts file as follows:

export default function Home() {
  return (
    <div>
      <h1>Auth.js behind a proxy</h1>
      <p>A step-by-step for using Auth.js in a subpath behind a Netlify proxy</p>
      <a href="/authjs">Go to Auth.js app</a>
    </div>
  );
}

Configure Netlify redirect rule

Create a _redirects file in the /public directory with the following content:

/authjs/* https://next-auth-behind-proxy.vercel.app/authjs/:splat 200!

Deploy the project on Netlify

To deploy your project on Netlify, you can follow these steps:

  1. Push your project to GitHub.
  2. Register for a free Netlify account at https://app.netlify.com/signup.
  3. Log in to Netlify using your GitHub account.
  4. Click on "New site from Git".
  5. Select the GitHub repository you want to deploy.
  6. Configure your site settings, such as the site name and build command.
  7. Click "Deploy site".

Your project should now be deployed on Netlify.

Configure Next.js configuration for the next-auth app

To create a new repository from the Next.js starter template for NextAuth.js, follow these steps:

  1. Go to the NextAuth.js starter template repository.
  2. Click on the "Use this template" button.
  3. Choose a name for your new repository and select any other options you want.
  4. Click on the "Create repository from template" button.

Your new repository will be created with all the necessary files to get started with NextAuth.js.

Configure the next-auth app with custom basePath and trailingSlash in your next.config.js file:

const isProd = process.env.NODE_ENV === "production";

module.exports = {
  trailingSlash: true,
  assetPrefix: isProd ? process.env.NEXT_PUBLIC_ASSET_PREFIX : undefined,
  basePath: process.env.NEXT_PUBLIC_ASSET_PREFIX,
};

Configure next-auth

Configure next-auth like this in your /pages/api/auth/[...nextauth].ts file:

import NextAuth from "next-auth";
import Providers from "next-auth/providers";

export default NextAuth({
  providers: [
    Providers.GitHub({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
});

Before deploying, we want to set the environment variables first.

Override x-forwarded-host header

For this setup to work, we need to set NEXTAUTH_URL and override the x-forwarded-host header using Advanced Initialization:

NEXTAUTH_URL="https://authjs-with-proxy.netlify.app/authjs/api/auth/"
import NextAuth from "next-auth";
import Providers from "next-auth/providers";

export const authOptions = {
  providers: [
    Providers.GitHub({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
};

export default function auth(req: NextApiRequest, res: NextApiResponse) {
  req.headers["x-forwarded-host"] = process.env.NEXTAUTH_URL;
  return NextAuth(req, res, authOptions);
}

GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET

First, we need to create a new GitHub OAuth app. Follow these steps:

  1. Go to https://github.com/settings/developers.
  2. Click on "New OAuth App".
  3. Fill in the details for your app, such as the name, homepage URL, and callback URL.
  4. For the callback URL, enter https://your-netlify-app.netlify.app/authjs/api/auth/callback/github.
  5. Click on "Register application".
  6. Copy the Client ID and Client Secret to put in the Vercel project settings as GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET. From the Vercel dashboard, select your project, and go to Settings → Environment Variables.

Deploy the next-auth app

To deploy the next-auth app to Vercel, you can follow these steps:

  1. Push your project to GitHub.
  2. Register for a free Vercel account at https://vercel.com/signup.
  3. Log in to Vercel using your GitHub account.
  4. Click on "Import Project".
  5. Select the GitHub repository you want to deploy.
  6. Configure your project settings, such as the project name and team.
  7. Click "Deploy".

Final touch

After following the above steps, you’re all set! However, there’s still one catch. After GitHub calls the callback endpoint, the Netlify redirect keeps the state and code parameters on the / page for some reason (related discussion here). To remove the params after being redirected, add this code to the next-auth app / as a workaround:

export default function Home() {
  const router = useRouter();
  useEffect(() => {
    if (router.query.code && router.query.state) router.replace("/", undefined, { shallow: true });
  }, [router.query]);
  return (
    <div>
      <h1>Auth.js behind a proxy</h1>
      <p>A step-by-step for using Auth.js in a subpath behind a Netlify proxy</p>
      <a href="/authjs">Go to Auth.js app</a>
    </div>
  );
}

Conclusion

Thanks for reading - I hope this guide helps you with the setup. I will continue to work with the Netlify team to get rid of the workaround for a cleaner setup. Until then, keep rocking 🤘