Next.js REST API Is Easy. Here’s How To Add It to Your Project

So Steve
2 min readApr 1, 2021

Prelude

My frequent web stack looks like this: Next.js + Vercel + Node.js + Heroku. It’s been a standard for most of my recent projects. Billisfun.com is an example.

However, I started working on a new project and wanted to decrease my stack a bit without adding limitations. Specifically, I wanted to have some server side functions accessible from a chrome extension without creating a new Heroku server. Heroku is great, but setting a separate back-end is always extra effort.

That’s how I stumbled upon an info that I could create a Rest API with Next.js and run my functions on Vercel without Heroku. But is it that simple, I asked myself.

Turns out, it is simple

So let me show you how this REST API was achieved. It’s not more difficult than your usual Next.js API Routes. I just added CORS Configuration Options. All this config does is allows your Next.js app to communicate with outside sources (in my case a Chrome extension).

If you never used API Routes with Next.js all you have to do it to create a page inside projectName/pages/api/greeting.js (replace greeting with whatever your heart desires)

//greeting.jsexport default function handler(req, res) {
res.status(200).json({ greeting: 'Hello World!' })
}

If you run your app locally and make a GET request (http://localhost:3000/api/greeting) you will get a JSON response { greeting: ‘Hello World!’ }. The problem with the current setup is that it won’t allow you to get the same response if you make it from another domain (like https://reqbin.com). How to solve it? CORS configuration!

CORS

First we need to import a middleware that will help us with it. Here’s how the file looks like:

//init-middleware.jsexport default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}

It’s recommended to place this file in the lib folder (projectName/lib/init-middleware.js)

Then we need to edit our API file (in my case it’s pages/api/greeting.js) to use the middleware. After the change your file will look like this.

import Cors from "cors";
import initMiddleware from "../../lib/init-middleware";
const cors = initMiddleware(
Cors({
methods: ["GET", "POST", "OPTIONS"],
origin: "*",
credentials: true
})
);
export default function handler(req, res) {
await cors(req, res);
res.status(200).json({ greeting: 'Hello World!' })
}

✅ Done

Now your REST API can be accessible from anywhere in the world. I think REST API by Next.js is a great solution if you want to build a simple app that will serve API requests from all over the web. So don’t sweat about it and implement it on your next project where you think you have to have a back-end server.

--

--