How to type Next.js env variables in TypeScript
Krzysztof Żuraw

Krzysztof Żuraw @kzuraw

About: TypeScript & React + V60

Location:
Wrocław
Joined:
Oct 20, 2017

How to type Next.js env variables in TypeScript

Publish Date: Sep 8 '22
35 7

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

Comments 7 total

  • Nikita Dovhich
    Nikita DovhichMay 1, 2023

    Thanks, your post helped a lot : )

  • aminsoraya
    aminsorayaJun 6, 2023

    you save many of my times.

  • Hanzla Haroon
    Hanzla HaroonJul 18, 2023

    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.

  • Clarance Liberi 💯
    Clarance Liberi 💯Aug 2, 2023

    Saved my day. much love :)

  • Reinaldo Vombo
    Reinaldo VomboJan 6, 2024

    you are life saver

  • Jon James
    Jon JamesJan 14, 2024

    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
    • tocaherge
      tocahergeFeb 28, 2024

      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.

Add comment