Skip to content

Confused about usage of process.env  #22266

@damianon

Description

@damianon

What version of Next.js are you using?

10.0.5

What version of Node.js are you using?

14

What browser are you using?

Firefox

What operating system are you using?

Windows

How are you deploying your application?

cross-env NODE_ENV=production node server.js

Describe the Bug

I'm very confused about the use of process.env. Variables.
(Here in the docs)[https://nextjs.org/docs/basic-features/environment-variables] it says 'In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time.' However looking into my docker container (or the locally compiled code) in the .next folder i can clearly still see process.env.VAR_NAME in all the places, and runtime environment variables are used. (all our pages are serverside rendered, not statically)

While this is mostly what I want, there are two cases where i want build time fixed variables, so looking into it, it's not very clear how this can be achieved.

Also under the (runtime variables docs)[https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration] it suggests using serverRuntimeConfig/publicRuntimeConfig together with getInitialProps which however is aparently deprecated in favor of getServersideProps. Also when I tried using this mapping in the next.config.js using the next config on a page always returned both of these as empty arrays (public and server).

So I have as of now no clue at all on how to achieve both runtime and build time environment variables. So far in my project process.env. seems to be runtime and serverRuntimeConfig didn't work at all.

If process.env. is in fact runtime, that's fine, but then the docs are wrong in stating it's build time.

server.js is just a express wrapper for next:

app.prepare().then(() => {
    const server = express();

    server.use(
        /api/,
        createProxyMiddleware({
            target: process.env.API_ENDPOINT,
            changeOrigin: true,
        })
    );

    server.all('*', (req, res) => handle(req, res));

    server.listen(port, (err) => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });
});

Expected Behavior

A clear way on how to use environment variables defined at build time and at runtime. (e.g. i want the version to be fixed at build time, but some connection strings at runtime)

To Reproduce

Use process.env. variables somewhere in pages or components.
run next build
inspect .next generated code and still find process.env (even if the docs state the opposite)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue was opened via the bug report template.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions