Next.js: Env property undefined in deployed serverless function

Created on 27 May 2020  ยท  5Comments  ยท  Source: vercel/next.js

Describe the bug

I am connecting to my database in a serverless function. This works locally, but not once deployed. My database connection string is stored in a .env file. When deployed this string is undefined. The env file is committed and in the repo.

Github repo example - https://github.com/AshConnolly/next-env-issue

Here is my example .env file:

API_KEY='default-api-key'
CLIENT_KEY='default-client-key'
NEXT_PUBLIC_APP_LOCALE='en-us'
TEST='test'

When outputted into a page:

  <li>API_KEY='default-api-key' : {process.env.API_KEY}</li>
  <li>CLIENT_KEY='default-client-key' : {process.env.CLIENT_KEY}</li>
  <li>NEXT_PUBLIC_APP_LOCALE='en-us' : {process.env.NEXT_PUBLIC_APP_LOCALE}</li>
  <li>TEST='test' : {process.env.TEST}</li>

It shows only the value NEXT_PUBLIC_APP_LOCALE - as expected โˆš.

However in a serverless function, it does not read my env variables correctly.
This is what my serverless function looks like:

export default async (req, res) => {
  res.setHeader('Content-Type', 'application/json')
  res.statusCode = 200
  res.json({
    API_KEY: process.env.API_KEY,
    CLIENT_KEY: process.env.CLIENT_KEY,
    NEXT_PUBLIC_APP_LOCALE: process.env.NEXT_PUBLIC_APP_LOCALE,
    TEST: process.env.TEST,
  })
}

Expected behavior

Locally this shows correctly when i visit http://localhost:4000/api/test, outputting:

{
"API_KEY": "default-api-key",
"CLIENT_KEY": "default-client-key",
"NEXT_PUBLIC_APP_LOCALE": "en-us",
"TEST": "test"
}

Actual behavior when deployed

However when deployed it does not. it only shows the NEXT_PUBLIC_APP_LOCALE -
```js
{
"NEXT_PUBLIC_APP_LOCALE": "en-us"
}
````

To Reproduce

Github repo - https://github.com/AshConnolly/next-env-issue
Run locally, and deploy it to vercel to see the issue.

System information

Not applicable as its the deployment issue.

Why is this happening?
Thanks! ๐Ÿ‘

Most helpful comment

It was released on stable last night ๐Ÿ‘

All 5 comments

Hi, this sounds like a duplicate of https://github.com/zeit/next.js/issues/13332 which was resolved by https://github.com/zeit/next.js/pull/13406 and is available in >= v9.4.3-canary.1 of Next.js

Great! Thanks @ijjk! Do you have a rough estimation of how long it will be until that fix is released to master?

This should be available on master now in v9.4.3 of Next.js

It was released on stable last night ๐Ÿ‘

You heroes! Thanks @ijjk @timneutkens! ๐Ÿ˜„

Was this page helpful?
0 / 5 - 0 ratings