Loading...

How to create global types in Typescript in a Next.js app?

question nextjs react
Ram Patra Published on July 9, 2024
Tested on Next.js 14

The env.d.ts file is typically used for global type declarations, especially for environment variables and other globally available types. This file is automatically included in the TypeScript compilation if it’s referenced in tsconfig.json.

Steps to Use env.d.ts:

  1. Create env.d.ts: Create an env.d.ts file at the root of your project or within a types directory.

    // env.d.ts
    declare namespace NodeJS {
      interface ProcessEnv {
        NEXT_PUBLIC_API_URL: string;
        NEXT_PUBLIC_ANALYTICS_ID: string;
        // Add other environment variables here
      }
    }
    
  2. Include env.d.ts in tsconfig.json: Ensure env.d.ts is included in the TypeScript compilation by adding it to the include array in tsconfig.json.

    // tsconfig.json
    {
      "compilerOptions": {
        "target": "esnext",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "baseUrl": ".",
        "paths": {
          "@/*": ["./*"]
        }
      },
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "env.d.ts"],
      "exclude": ["node_modules"]
    }
    

Differences Between env.d.ts and Custom Types in a Separate File:

  1. Purpose and Scope:
    • env.d.ts: Used for global declarations, particularly environment variables and extending global namespaces.
    • Custom Type Files (e.g., types/types.ts): Used for defining custom types, interfaces, and types specific to your application’s domain logic.
  2. Modularity:
    • env.d.ts: Typically holds global declarations that need to be available throughout the project.
    • Custom Type Files: Can be organized modularly, allowing you to create multiple files for different parts of your application (e.g., user.types.ts, product.types.ts).
  3. Usage:
    • env.d.ts: Automatically included in the TypeScript compilation, no need to import types declared here.
    • Custom Type Files: Types must be explicitly imported where they are used, promoting clearer dependencies and better modularization.

Example of Using Both Approaches:

  1. env.d.ts for Environment Variables:

    // env.d.ts
    declare namespace NodeJS {
      interface ProcessEnv {
        NEXT_PUBLIC_API_URL: string;
        NEXT_PUBLIC_ANALYTICS_ID: string;
      }
    }
    
  2. types/user.types.ts for Custom Types:

    // types/user.types.ts
    export interface User {
      id: number;
      name: string;
      email: string;
    }
    
    export type UserRole = 'admin' | 'user' | 'guest';
    
  3. Including env.d.ts in tsconfig.json:

    // tsconfig.json
    {
      "compilerOptions": {
        // other options
      },
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "env.d.ts"],
      "exclude": ["node_modules"]
    }
    
  4. Using Custom Types in a Component:

    // app/page.tsx
    import { User, UserRole } from '../types/user.types';
    
    const HomePage = () => {
      const user: User = {
        id: 1,
        name: 'John Doe',
        email: '[email protected]'
      };
    
      const role: UserRole = 'admin';
    
      return (
        <div>
          <h1>Welcome, {user.name}</h1>
          <p>Your role is: {role}</p>
        </div>
      );
    };
    
    export default HomePage;
    

Summary

Using env.d.ts is ideal for global type declarations and environment variables, while defining custom types in separate files is better for modularity and maintainability of your application’s specific types. Both approaches can be used in conjunction to achieve a well-organized and type-safe codebase in a Next.js TypeScript project. For creating app specific types, read this blog.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on July 9, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question nextjs react July 9, 2024 How to define an enum in Typescript and use it in a Next.js app?

Creating an enum in TypeScript within a Next.js project is straightforward. Enums in TypeScript allow you to define a set of named constants that can be used to represent a collection of related values. Here’s how you can create and use an enum in a Next.js application:

question typescript react September 28, 2024 How to add a custom element to a Next.js/Typescript project?

Let’s say I have a custom element setapp-badge that I want to use in my tsx files. If I go ahead and use it, the compiler will throw an error and Next.js will fail to build. It seems the problem might be a combination of how Next.js, TypeScript, and custom elements work together. Therefore, let’s try an approach that avoids the namespace/module issues while ensuring custom elements are recognized in a Next.js/TypeScript project.

question nextjs cloudflare March 19, 2025 How to run a website built with Next.js 15 on Cloudflare Pages?

If you simply connect a website’s code on GitHub with Cloudflare Pages that’s built using Next.js 15+, it may not build successfully out of the box. If this is the case with you, make sure to do the following.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.