Max Schmitt

February 27 2023

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:


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)

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.