Ibra
Ibra

Reputation: 1046

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

I’m making a website via Next.js. Next.js provides SSR and dynamic routing.

I think next build & next start show pages as well as I expected.

Upvotes: 39

Views: 29812

Answers (3)

Clifford Fajardo
Clifford Fajardo

Reputation: 1447

Short Answer

You do not need to use Express to use Next.js out of the box; the vast majority of people don't.


Long Answer

If you are not hosting on Vercel's platform, for example self-hosting (AWS,Digital Ocean, Azure etc...) you optionally have the ability to define a custom Next.js server and swap the underlying server implentation/framework (to use Express, Fastify, vanilla Node etc).

When might a custom server be a good idea?

  • when you're not hosting on Vercel
  • when you have custom requirements & custom existing infrastructure

Scenario: Imagine a large company that has lots of custom built infrastructure (logging, AB testing, custom linters etc) they've built over the years. They now want to take advantage of some of Next.js abstractions like:

  • different SSR rendering strategies
  • modern/flexible build system
  • all the other stuff you would need to implement from scratch, maintain, test...

Let's call this company XCompany. XCompany uses Express.js (doesn't matter which node server/framework) for their web server. They want to continue using Express.js since they've invested lots of time, resources building custom infrastructure and tools to work with it like AB testing integration, logging middlewares etc.

A custom server would allow XCompany to continue using Express without a complete re-write change and still benefit from the stuff Next.js that next offers SSR, the build system etc, nice conventions & guardrails etc. At end of this response I linked to Lyft's engineering blogpost of their migration to using Next.js with their own infra.

When you self-host your server and deploy it to your on infrastructure you get a long running node server, which is different from hosting on Vercel, where the server is a serverless function.

Context/History

Next.js under the hood uses vanilla HTTP server. If you would like to get similar express functionality like the way routes are setup/organized you can use a package like next-connect.

Express use to rely on the connect package directly. Most Node.js servers follow connect like API for routing & setting up handlers.

For folks coming outside of the Node.js world (Python / Flask), the connect style of organizing server routes is sort of like WASGI - Web Server Gateway Interface in philosophy.

Cons/Challenges of using Custom Next.js Server?

  • initial time investment learning custom Next.js server patterns.
  • The vast majority of people don't go down this route so documentation is more scarce
  • if you're not hosting on Vercel you don't get serverless functions. This may not be con or downside, if you don't have a serverless use case.
  • For example, if you're web server will be using websockets / WebtRTC which require persistent long running connections between client and server than serverless function's aren't the best choice here; there are workarounds, but I still think its not the best use case. Note, you can still use add on serverless features to your custom server through another provider (AWS, Azure, etc).

Moving Forward Most JS runtimes have been converging on exposing & using the Request & Response object APIs and exposing them to consumers.

Note, there's a ton of stuff that could be talked about here. Please leave follow up questions & I will try to update this answer accordingly


Resource(s)

Upvotes: 25

Yilmaz
Yilmaz

Reputation: 49401

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.

Upvotes: 37

Cássio Lacerda
Cássio Lacerda

Reputation: 1634

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.

Upvotes: 10

Related Questions