Web Overflow

Web Overflow

search
menu
Home

Home

Community

Community

Collections

Collections

Find Jobs

Find Jobs

Tags

Tags

Ask a question

Ask a question

Top Questions

How to center a div?chevron rightBest practices for data fetching in a Next.js application with Server-Side Rendering (SSR)?chevron rightAsync/Await Function Not Handling Errors Properlychevron rightAsync/Await Function Not Handling Errors Properlychevron rightHow can we eliminate the illusions in Large Language Models?chevron right

Popular Tags

javascript

5

css

4

nextjs

3

react

2

html

1

    profile picture

    Alfie Chen

    upvote

    1

    downvote

    0

    star

    How do I use express as a custom server in NextJS?

    clock icon

    asked 9 months ago Asked

    message

    1Answers

    eye

    7Views

    I currently have a server.ts file.

    const { createServer } = require('http')
    const { parse } = require('url')
    const next = require('next')
     
    const dev = process.env.NODE_ENV !== 'production'
    const hostname = 'localhost'
    const port = 3000
    // when using middleware `hostname` and `port` must be provided below
    const app = next({ dev, hostname, port })
    const handle = app.getRequestHandler()
     
    app.prepare().then(() => {
      createServer(async (req, res) => {
        try {
          // Be sure to pass `true` as the second argument to `url.parse`.
          // This tells it to parse the query portion of the URL.
          const parsedUrl = parse(req.url, true)
          const { pathname, query } = parsedUrl
     
          if (pathname === '/a') {
            await app.render(req, res, '/a', query)
          } else if (pathname === '/b') {
            await app.render(req, res, '/b', query)
          } else {
            await handle(req, res, parsedUrl)
          }
        } catch (err) {
          console.error('Error occurred handling', req.url, err)
          res.statusCode = 500
          res.end('internal server error')
        }
      })
        .once('error', (err) => {
          console.error(err)
          process.exit(1)
        })
        .listen(port, () => {
          console.log(`> Ready on http://${hostname}:${port}`)
        })
    })

    I'm not sure how to incorporate Express or Fastify without errors.

    nextjs
    express
    javascript

    1 Answers

    profile picture

    Alfie Chen

    answered 9 months ago

    upvote

    1

    downvote

    0

    To incorporate Express or Fastify into your existing server.ts file, you can replace the code that sets up the basic HTTP server with the code to create an Express or Fastify server and then delegate the handling of requests to Next.js for handling the routing and rendering.

    Here's an example of how you can integrate Express into your existing server.ts file:

    const { createServer } = require('http');
    const { parse } = require('url');
    const next = require('next');
    const express = require('express');
    
    const dev = process.env.NODE_ENV !== 'production';
    const hostname = 'localhost';
    const port = 3000;
    
    const app = next({ dev, hostname, port });
    const handle = app.getRequestHandler();
    const server = express();
    
    app.prepare().then(() => {
      server.all('*', (req, res) => {
        const parsedUrl = parse(req.url, true);
        const { pathname, query } = parsedUrl;
    
        if (pathname === '/a') {
          return app.render(req, res, '/a', query);
        } else if (pathname === '/b') {
          return app.render(req, res, '/b', query);
        } else {
          return handle(req, res, parsedUrl);
        }
      });
    
      server.listen(port, () => {
        console.log(`> Ready on http://${hostname}:${port}`);
      });
    });



    In this modified code snippet, we replaced the createServer function with an instance of Express server. We then use server.all to capture all incoming requests and delegate the routing logic to Next.js by calling app.render or handle.

    You can follow a similar approach to integrate Fastify by replacing Express with Fastify and adjusting the routing logic accordingly.

    Feel free to ask if you need further clarification or more detailed examples.