• Join StackChief
  • Blog
  • Tutorials
  • Questions
  • React
  • JavaScript
  • MongoDB
  • NodeJs
  • Kafka
  • Java
  • Spring Boot
  • Examples

Blog

NextJS Examples | Express

NextJS Examples | Starter

NextJS Examples | Layout

NextJS Examples | Express

NextJS Examples | MongoDB

This post shows you how to integrate an Express app into your Next.js starter project effectively.


Key Takeaways

  • Set up a custom server using Express to manage routing with Next.js.
  • Use nextApp.prepare() to configure your Next.js server before handling any requests.
  • Update your package.json scripts to align with your Express integration.
  • Forward requests seamlessly from Express to Next.js using the custom handler.

Setting Up the Express Server

Create a server.js file at the root of your Next.js project. This file will serve as the main entry point.

Here’s an updated example of an Express configuration within your server.js file:

const express = require('express');
const next = require('next');
const posts = require('./api/post');

// Next.js configuration
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();

nextApp.prepare().then(() => {
  const app = express();

  // Middleware for handling JSON data
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));

  // Define custom API routes
  app.use('/posts', posts);

  // Catch-all route for Next.js /pages
  app.all('*', (req, res) => {
    return handle(req, res);
  });

  app.listen(process.env.PORT || 3000, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${process.env.PORT || 3000}`);
  });
});

Note that we now use express.json() and express.urlencoded() for JSON parsing, as the body-parser module is no longer necessary.

Integrating Next.js Routing

We define the Next.js app instance like this:

const nextApp = next({ dev });

The prepare() method initializes the server, setting it up based on the environment (development or production). This setup is essential before handling requests.

All requests fall back to Next.js pages if not explicitly handled by Express, thanks to this catch-all route:

app.all('*', (req, res) => {
  return handle(req, res);
});

We've updated it to app.all('*') for full method coverage.

Forwarding Requests to Next.js

You can directly forward requests to Next.js from within an Express route to render a specific page:

app.get('/post', (req, res) => {
  return nextApp.render(req, res, '/post');
});

This forwards the request to your pages/post.js file, allowing Next.js to render it accordingly.

Updating package.json

Adjust your package.json scripts to refer to your custom server.js:

"scripts": {
  "dev": "node server.js",
  "test": "jest",
  "build": "next build",
  "start": "NODE_ENV=production node server.js"
}

By pointing the dev and start scripts to server.js, you initiate your application through Express, leveraging custom routes and middleware.

FAQ

Why use Express with Next.js?

Express provides a flexible way to add custom APIs and middleware, making it easier to build complex server-side logic that complements Next.js pages.

What has changed with body parsing in Express?

As of Express 4.16.0, body parsing functionalities are built into Express, so you don't need the body-parser middleware separately.

How do you handle custom API routes?

You can define API routes using Express's routing capabilities and integrate them seamlessly within the Next.js project structure.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews
Comment