Express Vs Next Js

Posted on  by admin

Editor’s Note: This blog post was updated with relevant information and code blocks in October 2021. It goes without saying that React is an excellent choice for building high-quality web applications.

However, as your projects become more complex, you’ll need to learn about client-side routing, page layout, and so on to scale your applications.

At some point, you’ll want your pages to load faster, for example. Oftentimes, this is where things can become difficult. Next.js is a universal JavaScript framework that runs in both the browser and the server. It offers developers an easy way to get started, and, because it uses React for templating, it is also a straightforward way for developers with React experience to get productive fast.

Getting started with Next.js

One of its strong points is that it handles server-side rendering excellently, and it integrates with Express just well. Oh, how I love Express. But we’re getting ahead of ourselves. Let’s talk about why you need server-side rendering in the first place. Then we’ll start building things. Next.js is an open-source development framework built on top of Node.js, enabling React-based web applications functionalities such as server-side rendering and allowing the ability to generate static websites.

Some ExpressJS features are:

It was initially released on October 25, 2016, but has quickly become one of the go-to JavaScript frameworks when developers are looking to build high-quality web applications.

  • Next.js gives you the best developer experience with all the features you need for production, such as hybrid static and server rendering, TypeScript support, smart bundling, route pre-fetching, fast refresh, and built-in CSS support with absolutely no special configuration needed.

  • One of its strengths is that it handles server-side rendering excellently, and it integrates with Express just as well.

For us to fully take advantage of Next, we need to understand what server-side rendering is, how it works, and then get started to building our example server-side rendered React and Express web application.

Server-side rendering was the conventional method for getting your HTML up onto a screen. This refers to using a server environment to get your HTML up to the browser.

So why the fuss if it’s a conventional method that’s been around forever? Remember the introduction of MVC (model, view, controller) concept that caused some concern?

Basically, there was some disagreement that eventually brought about the rise of JavaScript frameworks for rendering views.

So what has this got to do with anything? Soon enough, a problem emerged: modern JavaScript frameworks only displayed a bunch of divs in the browser, using DOM manipulation to do its work around the browser. This meant that the user had to wait longer to see anything. It can also impact SEO if crawlers can’t see the content of the page quickly. One solution was to render the JavaScript files from the server before returning to its output to the server.

Getting started with Next is simple. Because it’s built on top of Node, go ahead and install Node v10.13 or later. You’ll also be using your text editor and terminal app for this tutorial. There are two ways we can create our application. The first method is what I recommend for this tutorial, as it’s ready to go out of the box.

The command above uses the tool called create-next-app, which bootstraps a Next.js app for you. It uses a default learning template specified through the --example flag.

Once this is done, run the development server:. Once this is done, navigate to http://localhost:3000, where you should see the example web application running:. First, start by using the following code:.

Next, open up your package.json and replace your script section with this:. Run the npm run dev command, you should get an error like:. This is because Next uses the pages directory and the files in them to map its routes. This means if we have a file called index.js in our pages folder, Next would try to use the component in it as our entry point.

Let’s create the pages folder and the index.js file.

Next, let’s add some code to the pages/index.js file:. Save the file above and run the command npm run dev in your terminal. If you visit your browser, see the text “Hello Next.js, this is your friend Brian from LogRocket” printed out on your browser.

200’s onlyMonitor failed and slow network requests in production

Notice how easy this is? No need to mount React to a div, no need to import React, no need to set up routes. In our usual React app, we would need to do other configs to allow for code-splitting and server-side rendering. But hey, view your page source. You’ll be amazed. It’s all done out of the box.

I bet you thought that was all the magic Next.js had in store. But Next went a step further by allowing better server-side rendering using Express for the tougher cases. First, add Express into your app:. Then create a file called ssr-server.js in your app and add the following content:. In the code block above, we imported the Express and Next libraries and created an instance passing in a boolean based on the environment which detects whether to launch Next.js in dev or production mode.

The app.getRequestHandler returns a request handler that we can use to parse all HTTP requests. The prepare function returns a promise, so we can add a .then pipe to it. In the .then call, we initiate Express, and we use a wild card route to catch all routes and return them to the handler function.

Now update your npm dev script to run the server-side rendering application entry point:. If you run npm run dev, your page would spin up looking the same as it was, but we can now easily achieve clean application routing now, as seen below:.

In the code above, we use the popular express routing to define such routes, then we pass the page that should be loaded and the id as a query param to the main Next app.

Using another framework

  • Here, the call /p?id=2 happens under the hood where no one can see what is going on. The regular user sees the URL as /p/2/. Now that we’ve developed our application, we’ll need to deploy it into a production environment.

  • First, we have to build the app. Then we can serve it using the command below:.

Wow, that’s cool. What if you want to export the app as a static HTML file?
  • Great question. First, create a file called next.config.js in the root of your app and add the following content:. Note: In the setup above, only the index page would be exported as it is the only route we have specified in the PathMap.

  • It’s also easy to add more pages if you need to. You can add a new key and value in the return object of the PathMap like '/about': { page: '/about' }.

Meet Express.js

  • Next, add the following to the scripts section of your package.json:. Finally, build and export your app. Next.js provides us with an extensive list of features that are easy to use and configure, such as clean routing, faster load time, improved SEO, and so much more.

  • You can learn more about Next.js from the official documentation. Modified3 months ago. 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?

Next.js provides the following key features:

I think next build & next start show pages as well as I expected. 113113 bronze badges. 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.

77 gold badges7474 silver badges113113 bronze badges. 113113 bronze badges. 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. 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.

11 gold badge1111 silver badges1313 bronze badges. 1313 bronze badges. You do not need to use express to use nextJS out of the box; the vast majority of people don't. 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.).

Not the answer you're looking for? Browse other questions tagged javascriptnode.jsexpressnext.jsserver-side-rendering or ask your own question.

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

An ideal example

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.

  • 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 connectionsbetween client and server than serverless function's arent the bestchoice here; there are work arounds, but i still think its not thebest use case.

  • Note, you can still use add on serverless features to your custom server through another provider (AWS, Azure, etc..). For example, if you're web server will be using websockets/WebtRTC which require persistent long running connectionsbetween client and server than serverless function's arent the bestchoice here; there are work arounds, but i still think its not thebest use case.

  • Note, you can still use add on serverless features to your custom server through another provider (AWS, Azure, etc..).

  • Moving ForwardMost 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. fastify-nextjs has example how to create a custom nextJS server using fastify.

  • How ExpressJS works under the hood. 11 gold badge1212 silver badges2424 bronze badges. 2424 bronze badges. While NextJS is a wonderful tool in its own right, augmenting it with Express makes for a really powerful combo.

  • Perhaps you have an existing Express API server and you wish to enable it to serve some front end with React/SSR. Or perhaps you want to write a chat application in NextJS, and you need to set up WebSockets.

  • Maybe you just want to take control of the routing, or run some express middleware and fetch standard data for your pages before they are served.

Conclusion

This type of set up is documented in NextJS itself: https://nextjs.org/docs/advanced-features/custom-server. In the standard example, they use Node's http package; we'll use Express to take advantage of its middleware and routing capabilities.

  • I've provided an example barebones integration - as a github template - at https://github.com/alexey-dc/nextjs_express_template. Let's take a look at some highlights. The main entry point is index.js, which sets up the environment and delegates spinning up the server:.

  • Note that I'm relying on dotenv to load environment variables - e.g. EXPRESS_PORT, NODE_ENV, and a few others. You can see the full list of necessary environment variables in the README in the github repository. In the server, both nextjs and express are initialzed, along with express midleware and a custom NextjsExpressRouter I built to take the routing over from NextJS into our own hands:.

The middleware I included is quite barebones, but serves as an example of what you might have in a real application:. The NextjsExpressRouter is really the heart of the integration. Let's take a closer look. The idea is to allow GET routes for pages to co-exist with API HTTP routes:.

Serving and exporting the app

I split out the API from the page routes into separate files, and I find that as the codebase grows, it helps to impose some sort of grouping or hierarchy on endpoints. Pages and API calls seem like the most basic organization. Note I made the init() function async.

In this case we don't need to run any I/O operations or other async initialization, but in the general case we might want to.

What is server-side rendering, exactly?

For my larger projects, the API typically itself has several sub-groups, and sometimes pages do as well. In this sample project that has very few routes, the API and pages are a flat list of routes:.

Obviously this is just a minimal sample API - all it does is allows you to read and increment an integer stored in memory on the server. The page routes showcase setting up a root / path, and a fallback * path - if we're not able to match the GET request, we default to what NextJS's standard behavior is: rendering pages by filename from the /pages directory.

Want to read more about React?

More than 500.000 people read our blog every year and we are ranked at the top of Google for topics such as React. If you liked this blog post and would love to read all our blog posts on React,