Using NextAuth with DEPLOY_PRIME_URL

Hi,

I am trying to deploy previews for a Next.js app with NextAuth on Netlify, specifically the Credentials provider of NextAuth. NextAuth generally needs the base URL of the website, in the NEXTAUTH_URL env variable, but the problem is that for preview deployment the URL is not static.

For Vercel, NextAuth can read VERCEL_URL if NEXTAUTH_URL is not found, see here. On Netlify, the equivalent would be, I think, DEPLOY_PRIME_URL but NextAuth doesn’t (yet) read that. Is there a way to dynamically define an env variable based on another, i.e. something like NEXTAUTH_URL: $DEPLOY_PRIME_URL?

Here is what I have tried:

  • Changing the build command:
[context.deploy-preview]
command = "export NEXTAUTH_URL=$DEPLOY_PRIME_URL && npm run build"

I think this doesn’t work because NextAuth needs the variable also at runtime in the serverless functions.

  • Using next.config.js to set it dynamically:
module.exports = {
  reactStrictMode: true,
  env: {
    NEXTAUTH_URL: process.env.DEPLOY_PRIME_URL,
  },
};

This didn’t work either, although I can’t tell why not, perhaps I did something else wrong or NextAuth really needs it as an env variable.

Thanks!

Hi @tsg

Functions only use environment variables defined in the UI explicitly.

As functions are built after the main build process, part of the build command (or a postbuild script) could output the required environment variables to a .env file which through the use of dotenv you could then access in the functions.

There is a very long detailed thread on using environment variables on Netlify which go into a lot more detail

1 Like

Thanks, @coelmay, with your tip I have added the following to netlify.toml and it works as expected:

[context.production]
command = "npm run build && echo \"NEXTAUTH_URL=$URL\" > .env.local"

[context.deploy-preview]
command = "npm run build && echo \"NEXTAUTH_URL=$DEPLOY_PRIME_URL\" > .env.local"
1 Like