Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • 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.

like image 396
Ibra Avatar asked Nov 07 '19 05:11

Ibra


People also ask

Is Express needed with NextJS?

Next. js doesn't replace Express and you can use them together. Next. js uses some Node.

Is NextJS better than express JS?

According to the StackShare community, ExpressJS has a broader approval, being mentioned in 843 company stacks & 759 developers stacks; compared to Next. js, which is listed in 79 company stacks and 66 developer stacks. Next. js is probably the most enjoyable React framework our team could have picked.

Do I need node with NextJS?

You don't need a node server running 24/7 for hosting your application. Also, if you don't use getServerSideProps, Next. js by default will pre-render your page, this page gets cached on a CDN. So yes you can make API calls to your PHP backend, without the need for a setting up a nodejs server yourself.

Why you shouldn't use NextJS?

Disadvantages of NextJS Although NextJS is developing rapidly and many features arrive, it still has some cons and issues which you can see below: Cost of flexibility – Next JS does not provide many built-in front pages, so you have to create the whole front-end layer from the ground up.


3 Answers

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
  • you can't deploy custom servers to vercel, but if you went down this route you're likely not going
  • 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)

  • how to deploy a nextjs custom server to another provider (not vercel)
  • fastify-nextjs has example how to create a custom nextJS server using fastify.
  • Changing Lanes: How Lyft is Migrating 100+ Frontend Microservices to Next.js
  • NextJS docs for Custom Server
  • npmjs - connect
  • npmjs - next-connect
  • How ExpressJS works under the hood
    • Video: From Scratch Express Routing
    • Express6 open source modern implementation of expressJS for educational purposes
like image 74
Clifford Fajardo Avatar answered Oct 09 '22 08:10

Clifford Fajardo


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.

like image 23
Yilmaz Avatar answered Oct 09 '22 07:10

Yilmaz


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.

like image 8
Cássio Lacerda Avatar answered Oct 09 '22 07:10

Cássio Lacerda