Do I have to use express in Next.js project? Do I have to use express in Next.js project? express express

Do I have to use express in Next.js project?


You do not need to use express, Next JS already has its own built-in server. However since express is popular, it is easier for developers to communicate with databases or handle other backend work.


Both, Next.js and Express.js are server side render solutions (SSR). However, you can integrate Next.js with Express.js with a custom server api, as stated in the documentation:

Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to integrate into an existing application. Next.js provides a custom server api.

const express = require("express");const next = require("next");const port = 3000;const dev = process.env.NODE_ENV !== "production";const app = next({ dev });const handle = app.getRequestHandler();app.prepare().then(() => {  const server = express();  server.get("/test", (req, res) => {    return app.render(req, res, "/test");  });    server.get("*", (req, res) => {    return handle(req, res);  });  server.listen(port, (err) => {    if (err) throw err;    console.log(`Ready on http://localhost:${port}`);  });});

In example, it's showed how to use get Express method to handle routes in a Next.js app. The code above will render the React component at /api/test when user points to http://localhost:3000/api/test and pass down req and res objects to render.