3

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?

2
  • 3
    Try next start & node server.js. There's also npm packages for things like this such as npmjs.com/package/concurrently. Commented Oct 27, 2019 at 17:46
  • Holy, thanks man it looks like I was adding an extra '&' and it wasn't working. Commented Oct 27, 2019 at 17:51

2 Answers 2

6

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`); }); }); 
Sign up to request clarification or add additional context in comments.

Comments

-1
  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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.