Tiago Martins
Tiago Martins

Reputation: 83

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?

Upvotes: 3

Views: 10829

Answers (2)

JustAG33K
JustAG33K

Reputation: 1556

  1. Install Concurrently npm package to your node dependencies.

    npm install concurrently
    
  2. Add the following scripts to node server's package.json

    "frontend-install": "npm install --prefix frontend",
    "start": "node server.js",
    "server": "nodemon server.js",
    "frontend": "cd ./frontend && npm run start",
    "dev": "concurrently \"npm run server\" \"npm run frontend\""
    

i am assuming that your next application is in a folder/directory called "frontend". 3. Add the following code to package.json of the nextjs application.

    "proxy": "http://localhost:5000"
  1. Now npm run start command to start node server and nextjs app together.

Upvotes: -1

KHB
KHB

Reputation: 646

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

Upvotes: 5

Related Questions