Max SchmittMS
12th February 2022

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

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.

Here is a super-easy way to add an API proxy with Next.js.

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) => {
proxy.web(req, res, { target: API_URL, changeOrigin: true })
}

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.