简体   繁体   中英

Conditional url based on NODE_ENV on Next.js

Is there a way for me to set an url based on whether I'm in development or production?

Currently I have a component with the following code:

export default class Search extends Component {
    static async getInitialProps({ query: { location } }) {
        const res = await fetch(
            `http://localhost:3000/api/search?location=${location}`
        )
        const businesses = await res.json()
        return businesses
    }
...
}

I would like something that allows me to do the following:

export default class Search extends Component {
    static async getInitialProps({ query: { location } }) {
        let res
        if (environment is in developement) {
          res = await fetch(
            `http://localhost:3000/api/search?location=${location}`
          )

        } else if (environment is in production) {
          res = await fetch (
            `https://productionurl.now.sh/api/search?location=${location}`
          )
        }
        const businesses = await res.json()
        return businesses
    }
...
}

You can do that using the NODE_ENV environment variable. For a nice developer experience, set up a config file like this:

/config/index.js

const dev = process.env.NODE_ENV !== 'production';

export const server = dev ? 'http://localhost:3000/api' : 'https://productionurl.now.sh/api';

Then you can use that inside your getInitialProps methods throughout your application.

/components/Search.js

import { server } from '../config';

// ...

static async getInitialProps({ query: { location } }) {
  const res = await fetch(`${server}/search?location=${location}`);
  const businesses = await res.json();
  return businesses;
}

Make sure that the NODE_ENV variable is set inside package.json build scripts, which should look something like this.

package.json

"scripts": {
  "build": "NODE_ENV=production next build",
},

Yes, like what alex bennett has commented, using dotenv should work for your case!

To set it up,

  1. Install dotenv as a dependency on your Node.js project npm install dotenv --save then require it in your application require('dotenv').config()

  2. Create a file called .env in the root directory of your project with the environment variables that you need in this <NAME>/<VALUE> format here: MY_ENVIRONMENT=production .

  3. Change <VALUE> to production if you're deploying from your hosted server, or to development if you're deploying from your localhost.

  4. When that's all set up, you can very easily check the loaded environment variables in your code like this (from your example):

export default class Search extends Component {
    static async getInitialProps({ query: { location } }) {
        let res
        if (process.env.MY_ENVIRONMENT === 'development') {
          res = await fetch(
            `http://localhost:3000/api/search?location=${location}`
          )

        } else if (process.env.MY_ENVIRONMENT === 'production') {
          res = await fetch (
            `https://productionurl.now.sh/api/search?location=${location}`
          )
        }
        const businesses = await res.json()
        return businesses
    }
...
}

Here's an example on how to setup development and production

const prodConfig = {
  publicRuntimeConfig: {
    API_ENDPOINT: 'http://google.com/api'
  }
}

const devConfig = {
  publicRuntimeConfig: {
    API_ENDPOINT: 'http://localhost:3000/api'
  }
}

module.exports = process.env.NODE_ENV === 'production ? prodConfig : devConfig

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM