Search code examples
next.jst3

use next.config.js environment variable from t3-env in nextjs


I am using t3-env package to typesafe my environment variable which is correctly working for .env file. But I have saved some env variables inside next.config.js also. How can I typesafe my next.config.js env variable.

/** @type {import('next').NextConfig} */
const nextConfig = {
  env: {
    siteName: 'The Custom Crow',
    facebookUrl: 'https://www.facebook.com/drippy.in/',
    twitterUrl: 'https://twitter.com/drippy_in',
    pinterestUrl: 'https://www.pinterest.com/drippy_in/',
    linkedinUrl: 'https://www.linkedin.com/company/drippy-in/',
    youtubeUrl: 'https://www.youtube.com/channel/UC2sDh9f6i7hjZx2i0rY3N8Q',
  },
  reactStrictMode: false,
};

module.exports = nextConfig;

my env.ts file

import { createEnv } from '@t3-oss/env-nextjs';
import { z } from 'zod';

export const env = createEnv({
  server: {
    DATABASE_URL: z.string().url(),
  },
  
  client: {
    NEXT_PUBLIC_BASE_URL: z.string().url(),
  },
  
  runtimeEnv: {
    // From .env file
    DATABASE_URL: process.env.DATABASE_URL,

    // From next.config.js, but it is showing error here
    siteName: process.env.siteName,
    facebookUrl: process.env.facebookUrl,
    twitterUrl: process.env.twitterUrl,
  },
});


Solution

  • Found a solution:

    inside env.ts

    export const env = createEnv({
      server: {
        DATABASE_URL: z.string().url(),
      },
      
      client: {
        NEXT_PUBLIC_BASE_URL: z.string().url(),
        NEXT_PUBLIC_siteName: z.string().min(1),
        NEXT_PUBLIC_facebookUrl: z.string().min(1),
        NEXT_PUBLIC_twitterUrl: z.string().min(1),
      },
      
      runtimeEnv: {
        // From .env file
        DATABASE_URL: process.env.DATABASE_URL,
    
        // From next.config.js, but it is showing error here
        NEXT_PUBLIC_siteName: process.env.siteName,
        NEXT_PUBLIC_facebookUrl: process.env.facebookUrl,
        NEXT_PUBLIC_twitterUrl: process.env.twitterUrl,
      },
    });