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 (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<