简体   繁体   中英

How can I run a node server with a next.js application?

I'm setting up a webapp in next.js that runs in parallel with a node express server which does some middleware work to interface with an API server.

I have everything working however I don't know how to make it all work together when making a npm run start. The only way it works is with a "node server.js" in one terminal and a "npm run start" in another.

I've tried to add a package.json script like this: "start-server": "next start && node server.js" but it only starts the next.js instance, and if I reverse the order then it only starts the node instance.

How do I make them both work so I can deploy this project?

Also since Next is a server-side package, you can build the next app to use your server.js code before deploying the server. like so:

/* eslint-disable no-undef */
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const options = {
  ...
};

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

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen('8700', err => {
    if (err) throw err;
    console.log(`> Ready on Port 8700`);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM