Need to set NEXTAUTH_URL dynamically as an Option for multi-domain/multi-tenant use

See original GitHub issue

Your question How to dynamically work with Passwordless/Email auth, without setting NEXTAUTH_URL.

What are you trying to do I am working on a use-case where NEXTAUTH_URL is not fixed at deploy-time or build-time, but run-time, for a multi-domain (single codebase) scenario. This is to have Email passwordless only.

I have had good success with next-auth other providers for usual scenarios, and absolutely love the simplicity.

Feedback I tried to browse around the code to get a sense of dependency of the deploy-time NEXTAUTH_URL, and it seems that it is use only to define the Url for sendVerificationRequest. If there was a way to pass it as an option, it would do it.

Please advise, whats the best approach.

  • Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:111
  • Comments:85 (15 by maintainers)

github_iconTop GitHub Comments

14reactions
a-typecommented, Feb 16, 2022

It’s kind of mind-boggling to me that this is still a problem. What is the advantage of only allowing the deployed host to be configurable via environment variable? Is there a technical consideration that prevents something as simple as NextAuth({ url: 'https://some-deployed.url' || process.env.NEXTAUTH_URL, ... });? Is anyone using a next-auth app with PR preview environment deploys?

Including a Vercel-specific workaround is asking non-Vercel users to abuse it in order to replicate the functionality in other providers which support NextJS perfectly well. We’re using Netlify. Unless maintainers are interested in accepting contributions which add special cases for each of the multitude of hosing environments, wouldn’t it be easier to place this configuration in the user’s direct control at runtime?

In Netlify, a preview app’s deployed URL isn’t known until build time, and that URL is also not available from the runtime environment (unfortunate, and Netlify’s own problem). There are a limited number of ways to expose that host to runtime function code, and one of them is to write it to a file during build, then import that file from the function.

To that end I’m forced to do this in Netlify in order to make next-auth work with our preview deploys:

  1. Create a file lib/deployedUrl.ts which by default exports a single deployedUrl constant. In the local environment this file is export const deployedUrl = 'http://localhost:3000';.
  2. Overwrite that file as part of the Netlify build using a script (this is Netlify’s fault, not related to this library):
const fs = require('fs-extra');
const path = require('path');

const filePath = path.resolve(__dirname, '../lib/deployedUrl.ts');

const deployedUrl =
  process.env.DEPLOY_PRIME_URL ||
  process.env.DEPLOY_URL ||
  process.env.NEXTAUTH_URL;

const fileContents = `export const deployedUrl = '${deployedUrl}';
process.env.NEXTAUTH_URL = deployedUrl;
`;

fs.writeFileSync(filePath, fileContents);

console.log('Done writing deploy url file\n', fileContents);
  1. Import that variable in pages/api/[...nextauth].ts
  2. Create the next-auth handler, but don’t export it directly. Wrap it in an outer handler which: a. Directly sets process.env.VERCEL = '1'; to trigger dynamic host functionality b. Sets req.headers['x-forwarded-host'] = new URL(deployedUrl).host; since Netlify doesn’t set this header for you
import { deployedUrl } from 'lib/deployedUrl';

// ...

const nextAuthHandler = NextAuth({
  // ...
});

// ...

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // force VERCEL env var which makes next-auth respect x-forwarded-host header
  process.env.VERCEL = '1';
  // brute force override host with deployed url
  req.headers['x-forwarded-host'] = new URL(deployedUrl).host;
  return nextAuthHandler(req, res);
}

Forgive my frustration (part of it is with Netlify not exposing that build-time environment to functions), but I would love to just pass url to the NextAuth handler options rather than having to intercept and modify the incoming request and runtime environment based on some internal implementation details I discovered by reading the library source.

Would the maintainers be open to a PR which exposes configuration for the deployed host directly to the user, falling back to existing behavior?

10reactions
duartegarincommented, Nov 25, 2022

Just commenting here to avoid the issue closing as I think it’s still very much relevant and quite surprising that it isn’t supported given it’s common practice in many SaaS software providers.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Need to set NEXTAUTH_URL dynamically as an Option for ...
I am working on a use-case where NEXTAUTH_URL is not fixed at deploy-time or build-time, but run-time, for a multi-domain (single codebase) ...
Read more >
How to Build a Multi-Tenant App with Custom Domains Using ...
Create a full-stack application with multi-tenancy and custom domain support using Next.js, Prisma, PlanetScale, and Tailwind CSS.
Read more >
Options | NextAuth.js
When deploying to production, set the NEXTAUTH_URL environment variable to the canonical URL of your site. ... If your Next.js application uses a ......
Read more >
Build cookie based auth for multi-tenant NextJS application
Also, this has the flexibility of setting custom options on the fly. For instance, if a cookie that you use in the app...
Read more >
How to implement NextAuth credentials provider with external ...
It can help you set up your authentication in minutes! However, for different reasons, you may need to implement your custom backend or ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found