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.
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