How do you access the URL in a NextJS app?

In my code I make API calls, but I want to be able to work with both dev and prod, so typically I would do something like:

let res = await fetch(`${process.env.SERVER_URL}/api/category/initialCategoryMeta?category=${category}`

How can I do something like this in NextJS so I can set SERVER_URL when running the app?


Build time config

module.exports = {
  env: {
    customKey: 'value',

This will allow you to use process.env.customKey in your code. For example:

function Index() {
    return <h1>The value of customKey is: {process.env.customKey}</h1>

export default Index

Run time configs

You can setup next.config.js file

// next.config.js
module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // Pass through env variables
  publicRuntimeConfig: {
    // Will be available on both server and client
    staticFolder: '/static',

And then access the values from next/config

// pages/index.js
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()

Next Runtime config

Leave a Reply

Your email address will not be published. Required fields are marked *