Javascript 如何在NextJS应用程序中访问URL?

Javascript 如何在NextJS应用程序中访问URL?,javascript,node.js,next.js,Javascript,Node.js,Next.js,在我的代码中,我进行API调用,但我希望能够同时使用dev和prod,因此通常我会执行以下操作: let res = await fetch(`${process.env.SERVER_URL}/api/category/initialCategoryMeta?category=${category}` 如何在NextJS中执行类似操作,以便在运行应用程序时设置服务器URL 构建时配置 这将允许您在代码中使用process.env.customKey。例如: function Index()

在我的代码中,我进行API调用,但我希望能够同时使用dev和prod,因此通常我会执行以下操作:

let res = await fetch(`${process.env.SERVER_URL}/api/category/initialCategoryMeta?category=${category}`
如何在NextJS中执行类似操作,以便在运行应用程序时设置服务器URL

构建时配置

这将允许您在代码中使用process.env.customKey。例如:

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

export default Index
然后从
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()

很抱歉,这没有解决开发与产品之间的问题,这解决了客户机与服务器之间的问题,这是非常不同的。@DanFein同样的方法,您可以为内置配置文件进行设置。这缺少很多信息,请在发布内容时更加清楚!
// 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',
  },
}
// pages/index.js
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()