Setting up API request routing in Next.js development environment

I’m new to Next.js and I’m trying to figure out how to route API requests during development. In my previous React projects using create-react-app, I used a setupProxy.js file to handle this. It worked great for routing API calls to a different port.

Now that I’m using Next.js, I’m not sure how to achieve the same thing. I’ve tried the same approach, but it’s not working. I keep running into errors.

I’ve looked online for solutions, and many suggest using a custom server. But I’d like to stick with the default Next.js dev server if possible. Is there a way to set up API request routing similar to what I did before, but using the standard next dev command?

Here’s a basic example of what I’m trying to do:

function configureProxy(server) {
  server.use('/api', (req, res) => {
    // Route API requests to a different port or URL
    // For example: http://localhost:8000
  });
}

// How can I use this with Next.js dev server?

Any help would be appreciated! I’m really stuck on this one.

yo, next.js api routes are cool but if u need external stuff, check out next.config.js rewrites. it’s like:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:8000/:path*',
      },
    ]
  },
}

this’ll proxy ur api calls. hope it helps!

hey there! ever tried next.js api routes? they’re neat, letting u create endpoints in pages/api. could that replace your proxy? what api calls are u using? curious about your setup.

Next.js handles API routing differently from create-react-app. Instead of using a setupProxy.js file, you can leverage Next.js’s built-in API routes feature. Create a file in the pages/api directory, and Next.js will treat it as an API endpoint.

For external API calls, you can use environment variables to manage different URLs for development and production. Set up a .env.local file with your API URL, then use process.env.API_URL in your fetch calls.

If you need more complex routing, consider using next.config.js to set up rewrites. This allows you to redirect requests without changing the URL visible to the user, which can be useful for API proxying during development.