Max SchmittMS
12th February 2022
27th February 2023 (updated)

Next.js: The Easiest Way to Create an API Proxy (2023)

If you're building a React website or application using Next.js, you might want to create a proxy for your API to prevent CORS issues.

Using Next.js Rewrites

The easiest way, is to use Next.js rewrites which were introduced in version 9.5.

const API_URL = process.env.API_URL
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: '${API_URL}/:path*'
}
]
}
}

Using the http-proxy Package

In older Next.js versions, you had to use a catch-all API route and the http-proxy package.

This is still an option if you want more fine-grained control over rewriting the request.

Step 1: Install http-proxy

First, we need the http-proxy package:

$ yarn add http-proxy

Step 2: Create Next.js API Route as Proxy

To proxy all requests at /api to your API, add the following file:

pages/api/[...path].js

import httpProxy from 'http-proxy'
const API_URL = process.env.API_URL // The actual URL of your API
const proxy = httpProxy.createProxyServer()
// Make sure that we don't parse JSON bodies on this route:
export const config = {
api: {
bodyParser: false
}
}
export default (req, res) => {
return new Promise((resolve, reject) => {
proxy.web(req, res, { target: API_URL, changeOrigin: true }, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}

And that's it! You can now make requests to your Next.js app at /api/* and those requests will be forwarded to your API at process.env.API_URL.

If you're dealing with an API that accepts authentication tokens as headers and you'd like to use http-only cookies instead, check out my post on Using HTTP-Only Cookies with Next.js.

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.