Published on

Writing Express-like Routes in Next.js with next-connect

Authors

Next.js does a pretty good job of handling API routes. However, if you're coming from Express World you might miss its simple route declaration.

Thankfully, we can have a similar route in Next.js as well with the help of next-connect

What is next-connect?

It's a routing and middleware layer for Next.js API. It supports pretty much everything thing in Next.js like:

  • Next.js API Routes
  • Edge API Routes
  • Middleware
  • Next.js App Router
  • getServerSideProps

Dependency

npm install next-connect@next

Example - Simple Router

// route-handler.js
import nextConnect from "next-connect";

const apiHandler = () => {
  return nextConnect({
    attachParams: true,
    onNoMatch: (req, res) =>
      res.status(404).send({
        ok: false,
        message: `API route not found: ${req.url}`,
      }),
    onError(err, req, res, next) {
      res.status(500);
      res.json({
        message: env !== "production" ? err.message : "Unexpected error",
      });
      console.error(err);
      // unexcepted error, catch with Sentry, etc.
    },
  });
};

export default apiHandler;
// auth-guard.js
// https://nesin.io/blog/nextjs-api-bearer-authentication
async function authGuard(req, res, next) {
  if (req.url.startsWith("/api/example/webhooks")) {
    next();
  }

  const authToken = (req.headers.authorization || "").split("Bearer ").at(1);
  // replace ADMIN_AUTH_TOKEN with your expected token
  if (authToken && authToken === process.env.ADMIN_AUTH_TOKEN) {
    next();
  }
  res.status(401).json({ error: "Invalid Auth Token" });

  next();
}

export default authGuard;
// pages/api/example/[[...path]].js
import apiHandler from "./api-handler"; // from the above snippet
import authGuard from './auth-guard'; // // from the above snippet

export default apiHandler()
  .use(authGuard)
  .get("/api/example", async (req, res) => {
    res.json({ message: "It's works", method: "GET" });
  })
  .post("/api/example", async (req, res) => {
    res.json({ message: "It's works", method: "POST" });
  })
  .put("/api/example", async (req, res) => {
    res.json({ message: "It's works", method: "PUT" });
  })
  .delete("/api/example", async (req, res) => {
    res.json({ message: "It's works", method: "DELETE" });
  });

Check out their readme, they've various snippets for other cases (with Typescript snippet)

Happy Express-like Next.js!