How to change a URL env variable based on the current preview's URL?

I have a Next.js app deployed on Netlify. I’m using Auth0 for authentication (nextjs-auth0), which requires an APP_BASE_URL environment variable when the app starts. This works fine for production and development deployments since APP_BASE_URL is fixed.

However, when I log in using a preview deployment, the base URL should match the dynamic PR preview URL (e.g., https://deploy-preview-150--project-name.netlify.app/, which corresponds to $DEPLOY_PRIME_URL in the build process). I haven’t found a way to set this variable dynamically per build.

If I set the variable in Netlify’s settings, it’s fixed for all preview deployments. I also tried adding a build command like:

echo APP_BASE_URL=$DEPLOY_PRIME_URL > .env && pnpm build && cp .env .next

but that didn’t work either.

Thank you so much.

.env should work, you don’t need to copy it manually though, Next Runtime would automatically do it for you.