I recently was setting up new Next.js project with environmental variables. Next supports them out of the box I wanted a bit more typing than string | undefined
. I couldn't find it easily on Google so I created this post.
First create env.d.ts
in root of your repository with environmental variables keys
namespace NodeJS {
interface ProcessEnv {
NEXT_PUBLIC_SUPABASE_URL: string;
NEXT_PUBLIC_SUPABASE_ANON_KEY: string;
}
}
Second add env.d.ts
to tsconfig.json
:
{
"compilerOptions": {
// options are here
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "env.d.ts"] // see the last entry in array
}
Top comments (7)
ProTip: Use
environment.d.ts
as the filename instead ofenv.d.ts
. It will be loaded automatically by Typescript. There will also be no need to manually add it totsconfig.json
.Thanks, your post helped a lot : )
you save many of my times.
Saved my day. much love :)
I found that when I did this using NextJs
14.0.4
, I had to import Next in the type file for TS intellisense in VSCode to work; in the end, myenvironment.d.ts
file:This helped for me. I just changed the import to
To prevent eslint being mad about unused variables.
you are life saver