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.
next.config.js
const API_URL = process.env.API_URL/** @type {import('next').NextConfig} */const nextConfig = {async rewrites() {return [{source: '/api/:path*',destination: `${API_URL}/:path*`,},]},}module.exports = nextConfig
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 APIconst 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.