t3-oss / t3-env

https://env.t3.gg
MIT License
2.67k stars 86 forks source link

Not able to get next.config.js environment variable #206

Closed rishabhchauhan421 closed 6 months ago

rishabhchauhan421 commented 7 months ago

Hi, I want 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 also.

next.config.js file

/** @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;

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,
  },
});
juliusmarminge commented 6 months ago

i don't know when next.js loads these into the environment so perhaps your best bet is to set them as shared variables in env.ts instead?

// env.ts
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(),
  },

  shared: {
    siteName: z.string(),
  },

  runtimeEnv: {
    DATABASE_URL: process.env.DATABASE_URL,
    siteName: "The Custom Crow",
  },
});
rishabhchauhan421 commented 6 months ago

Resolved:

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