Is there any way to read env vars in next.js middleware?

I everyone! I have some middleware set up in my next.js app, which I’m self hosting.

I’ve read through this guide, but it seems to have info on env vars, and info on middleware, but not info on both.

When I try to access process.env, I see variables that are available in my deployment, but not any of the NEXT_PUBLIC variables that I’ve set up myself.

I tried to load the env manually using this code.

import { loadEnvConfig } from '@next/env';

export function getProcess() {
    const projectDir = process.cwd();
    loadEnvConfig(projectDir);
    return process;
}

But then I get an error in my deployment (I think at build time)

A Node.js API is used (process.cwd at line: 356) which is not supported in the Edge Runtime.

Is there any way that I can access the env variables I’ve set up?

Thank you!

I found a solution to this. It seems like just having NEXT_PUBLIC variables do eventually end up available to middleware.

However it seems like these variables are not inlined for middleware, so they need to be resolved dynamically from the env. We had a problem with our docker image where .env files weren’t being copied, so they weren’t available to the middleware.

Not sure if that’s an expected or surprising behavior, but this seems solved for our context :+1:

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.