Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
Tiago Martins Avatar asked Jan 19 '26 02:01

Tiago Martins


1 Answers

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`);
  });
});

like image 166
K.H. B Avatar answered Jan 20 '26 17:01

K.H. B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!