In my previous post, I explained how I migrated my blog to Next.js. Today, I wanted to explore Next.js API Routes and how they can help us build a back-end for our front-end application.
You can find the demo project here
This post is part of a series which aim is to compare back-end solutions for Next.js. It is the first one and will be a reference for other implementations.
For the test to be relevant, the app should support the following features:
The tools I am interested in testing should support all these use cases, and also a GraphQL interface and/or type generation from the database model.
At the end of the test, I will outline relevant differences between all the solutions tested.
Next.js API routes are a built-in feature of Next.js. On top of serving your content, your server can also be used as a REST API!
This feature is particularly useful if you need to build a simple back-end, to add features to an existing API, or to consume libraries which are not available on the browser.
Since the feature is built into Next.js, we don't need any account or configuration, and will only need to code our API routes alongside our pages.
One great upside of Next.js API Routes is that they are Just JavaScript™️! You don't have to learn a specific syntax and can be proficient instantly if you know Express (and particularly the req
and res
objects).
Next.js API routes do not support GraphQL, but as this solution is only meant to be a reference for our future tests, this won't be a problem.
Here are the steps to implement a REST API using Next.js API Routes:
/pages/api
folder[requestName].ts
file in the pages/api
folder/api/[requestName]
(example here)Example:
import { readFileSync } from "fs";
import path from "path";
export default function handler(req, res) {
if (req.method !== "GET") {
res.status(404).send("Not found");
return;
}
const cocktails = JSON.parse(
readFileSync(
path.resolve("data/cocktails.json"), {
encoding: "utf-8",
}
)
);
res.status(200).json({ cocktails });
}
And that's it! No need to host your back-end, it will be hosted on the same server as your front-end!
As mentioned in the repository, the back-end implementation is quite naive, and the next steps will be to try other solutions such as MongoDB Realm, Amplify, Firebase, Prisma, ... You can follow me on Twitter to be notified once every new test comes out!