27

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

  • Do I have to use express?
  • If so, why do I have to use it?
  • What kind of features of express are useful that are not provided from Next.js?

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

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Ibra
  • 906
  • 1
  • 7
  • 13

3 Answers3

30

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.

Tahazzot
  • 1,224
  • 6
  • 27
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • 1
    is not Next use express under the hood? – mercury Dec 06 '20 at 21:09
  • 10
    It uses vanilla HTTP under the hood. But getting express functionality is easy using a package like `connect`. Express use to rely on the `connect` package. Most routers follow the connect like API https://www.npmjs.com/package/next-connect OR https://www.npmjs.com/package/connect – Clifford Fajardo Mar 19 '21 at 00:32
  • @cacoder from their package.json, it looks like NextJS uses Express under the hood... – Magne Jan 27 '22 at 20:40
  • Thanks for the update @magne - I think at the time they offered a vanilla JS server - awesome to hear express is in! – Clifford Fajardo Jan 28 '22 at 06:56
  • @cacoder I'm not sure though, so it'd be nice to have someone confirm/disconfirm it. Frankly, I'd have preferred if they'd used Fastify instead of Express: https://www.fastify.io/benchmarks/ (but that might not have been available at the time) – Magne Jan 29 '22 at 16:22
  • 1
    @cacoder I dived a bit into it. It seems they are still using their own server, from the [code](https://github.com/vercel/next.js/blob/canary/packages/next/server/next-server.ts) and from the [docs](https://nextjs.org/docs/advanced-features/custom-server). Seems like [Express is included](https://github.com/vercel/next.js/search?q=express) in their `package.json` for the custom server setup (and examples), aka. static server setups. – Magne Jan 31 '22 at 17:59
  • I think you guys are confusing the terms. express is not a server it is a framework – Yilmaz Jan 31 '22 at 18:08
  • I think I should update the answer in detail when I have time – Yilmaz Jan 31 '22 at 18:54
  • Thanks @yimalz - I agree 100% with you "express is a framework". Adding on, Express is also a library of plain javascript code that abstracts the plain HTTP module (in node) used to create a server. We can go down many levels of abstraction lol, to the point of "express/HTTP module is not a server but an abstraction on top of unix sockets". I think its fair to say Express is a server too? – Clifford Fajardo Feb 01 '22 at 18:13
18

Answer:

  • You do not need to use express to use nextJS 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 nextjs 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 NextJS 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 ExpressJS (doesn't matter which node server/framework) for their web server. They want to continue using ExpressJS 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 NextJS 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 NextJS 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

NextJS 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 nodejs servers follow connect like API for routing & setting up handlers.

For folks coming outside of the NodeJS 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 NextJS Server?

  • initial time investment learning custom nextJS 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 arent the best choice here; there are work arounds, 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)

Clifford Fajardo
  • 1,357
  • 1
  • 17
  • 28
  • 1
    "you can't deploy custom servers to vercel, but if you went down this route you're likely not going" ... going to what? Could you clarify this point a little? – Magne Dec 17 '22 at 13:41
9

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.

Community
  • 1
  • 1
Cássio Lacerda
  • 1,554
  • 1
  • 12
  • 14
  • 2
    Clarification: NextJS uses SSR (to render a React SPA on the server, and then wire it up again, aka. hydrate it, on the client). While Express is a low level server typically used for serving simple JSON API's or for classic server-rendering (templates). The distinction is a bit blurred since you can use Express with NextJS, although you don't have to since NextJS has its own low level server. – Magne Jan 31 '22 at 18:26