DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

How to type Next.js env variables in TypeScript

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

Collapse
 
hanzlaharoon profile image
Hanzla Haroon • Edited

ProTip: Use environment.d.ts as the filename instead of env.d.ts. It will be loaded automatically by Typescript. There will also be no need to manually add it to tsconfig.json.

Collapse
 
meliphyra profile image
Nikita Dovhich

Thanks, your post helped a lot : )

Collapse
 
aminsoraya profile image
aminsoraya

you save many of my times.

Collapse
 
claranceliberi profile image
Clarance Liberi 💯

Saved my day. much love :)

Collapse
 
jonjamesdesigns profile image
Jon James • Edited

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, my environment.d.ts file:

import Next from "next";

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      MY_CUSTOM_VAR: string;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tocaherge profile image
tocaherge

This helped for me. I just changed the import to

import "next";
Enter fullscreen mode Exit fullscreen mode

To prevent eslint being mad about unused variables.

Collapse
 
reinaldovombo profile image
Reinaldo Vombo

you are life saver