Environment variables are undefined in a custom server. For example in server.js
...
const app = next({dev});
console.log(process.env.MY_ENV_VARIABLE);
...
In next.config.js:
module.exports = {
env: {
MY_ENV_VARIABLE: 'hello',
},
};
Output:
undefined
I would like to be able to use environment variable in a custom server.
No
No
I'll post the same reply as here, as it applies in the same way: https://github.com/zeit/next.js/issues/12254#issuecomment-620460451
If you want to create API endpoints it's recommended to use API routes: nextjs.org/docs/api-routes/introduction. API routes are automatically compiled through Next.js' compilation pipeline and allow you to use import/export syntax and a bunch of other syntax that hasn't landed in Node.js yet, similar to pages.
If you use a custom server you're basically handing off a request to Next.js and Next.js is unaware of the server existing, it also boots up after the server boots up, meaning we can't compile the server, hence why you can only use Node.js features and Node.js currently does not compile import syntax.
I want to use a custom server.
This scenario is straight from the nextjs offical firebase authentication example. And is deployed on vercel. In server.js we need to use credentials from firebase.
Is there any alternative solution without pushing the private credentials to deploy?
I'm dealing with this same issue right now
dotenv is already automatically supported when you run next(), closing this as the new environment support sort of covers it: https://nextjs.org/blog/next-9-4#new-environment-variables-support
Most helpful comment
I'm dealing with this same issue right now