Search code examples
dynamicnext.jsenvironment-variableshostname

NextJs: How to use dynamic hostnames in api calls instead of .env variables


I am building a NextJs app: How to use dynamic hostnames in api calls instead of .env variables?

For example sometimes in my local dev environment the app sometimes runs in port 3001. How do I accommodate such scenarios by dynamically passing the appropriate hostname during requests?


Solution

  • I use next-absolute-url. From the docs:

    This module enables you to easily get the protocol and host of your Next.js app, both on the server and the client. Optionally, you can set a localhost variable, which is useful for local development if you have local lambda functions running on a different port.

      import absoluteUrl from "next-absolute-url";
    
      // in express we have req.get('host')
      const { origin } = absoluteUrl(req);