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

How do you access the URL in a NextJS app?

在我的代码中,我进行了 API 次调用,但我希望能够与开发人员和生产人员一起工作,因此通常我会执行以下操作:

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

我怎样才能在 NextJS 中做这样的事情,这样我就可以在 运行 应用程序时设置 SERVER_URL?

Build time config

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

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

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

export default Index

Run time configs

您可以设置next.config.js文件

// 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',
  },
}

然后访问 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