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;
  }
}

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
}