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`);
});
});
Install Concurrently npm package to your node dependencies.
npm install concurrently
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"
Now npm run start command to start node server and nextjs app together.
Related
I'm trying to deploy MERN stack app to Heroku, everything works fine except the landing page.
I tried every single solution I can but nothing worked.
Here is my app landing page, it displays blue screen with a button up top, if try to navigate to different routes like /contact or /plans it works fine.
I checked the logs and network requests everything is okay 200 status.
I tested the app on my machine and it worked as expected.
On Heroku it displays blue screen
Here is my server.js code
// Serve Static assests if in production
if (process.env.NODE_ENV === 'production') {
//set Static folder
app.use(express.static('frontUI/client/build'));
app.get('*', (req, res) => {
res.sendFile(
path.resolve(__dirname, 'frontUI', 'client', 'build', 'index.html')
);
});
}
here is my script
"scripts": {
"client-install": "npm install --prefix frontUI/client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix frontUI/client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild":
"NPM_CONFIG_PRODUCTION=false npm install --prefix frontUI/client && npm run build --prefix frontUI/client"
},
My landing page route
<Route
exact
path="/"
render={matchProps => (
<WithLayout
{...matchProps}
component={ServicesView}
layout={MainLayout}
/>
)}
/>
I have an react.js frontend application that is created with creact-react-app utility. I intend to run the app on a windows server machine and it has the following build/run tasks that are defined in my package.json file:
"scripts": {
"build:dev": "env-cmd -f .env.dev npm run build",
"build:test": "env-cmd -f .env.test npm run build",
"build:prep": "env-cmd -f .env.prep npm run build",
"build:prod": "env-cmd -f .env.prod npm run build",
"start-server": "env-cmd -f .env.prod node server/server.js"
}
So, for preparing my app for deployment on a windows server, I issue the following while I am inside the OS with an open command console:
npm run build:prod
npm run start-server
As a result of "npm run build:prod", the bundle is placed under my build directory in my project root. On the other hand, executing "npm run start-server" executes the following script, which is server/server.js.
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '..', 'build');
const port = process.env.REACT_APP_PORT;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log('Server has started listening at port ' + port);
});
Everything is fine until here, my application works but it keeps the command console busy. What I need is to run the app in the background and even if I log out windows, the app should continue to run and respond to requests. Moreover, it should start after windows restart. What would be the most convenient approach to realize this? I have read the create-react-app documentation but I did not get much help. In addition I noticed there is an npm package named pm2, but my corporate regulations dont let me install it unfortunately.
QUESTION: So, briefly I need your suggesstions on what would be the best practice approach to run my react.js front-end app at the background such that it keeps alive after log off and get restarted after windows restart? Thanks.
I am learning Node.js and this is my first code.
I created a file called server.js below with the code
server.js
const express = require('express');
const dotenv = require('dotenv');
//load env vars
dotenv.config({ path: './config/config.env'});
const app = express();
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);
I have this section in my package.json file
package.json
"scripts": {
"start": "NODE_ENV=production node server",
"dev": "nodemon server"
},
Here is the content of my config.env file
config.env
NODE_ENV=development
PORT=5000
When I run npm run dev everything is fine and runs
When I run npm start to run production, I get the error below.
'NODE_ENV' is not recognized as an internal or external command,
operable program or batch file.
How can I resolve this? I need npm start to run
For Windows:
"scripts": {
"start": "node server.js",
"dev": "set NODE_ENV=DEVELOPMENT && node server",
"prod": "set NODE_ENV=PRODUCTION && node server"
}
For UNIX and other OS:
"scripts": {
"start": "node server.js",
"dev": "export NODE_ENV=DEVELOPMENT && node server",
"prod": "export NODE_ENV=PRODUCTION && node server"
}
By the error message, you are running this in Windows. You need to use Set to setup an environment variable.
"scripts": {
"start": "Set NODE_ENV=production&node server",
"dev": "nodemon server"
}
However, setting up environment variables in this manner is less secure and platform dependent. In other words, any attacker getting access to your server file system can set any environment variable by modifying the package.json. Also, if you decide to move your production to a Linux host later, your start script is going to be broken again.
So, the best practice is to set your environment variables via host configuration setup. Different cloud providers offer different methods for this.
Also, you might not need to use npm to run your script at all. You can call node server directly in your shell.
An easy way to solve this problem:
npm install --save-dev cross-env
"start": "cross-env NODE_ENV=production node server"
This means that you don't have to worry about the platform
for read more: https://www.npmjs.com/package/cross-env
hi i have a nodejs and reactjs application in my local , developed the application from a boiler plate code , in boiler plate code package.json i have these following scripts
"scripts": {
"client-install": "npm install --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
}
as of i know it can be deployed on heroku with these scripts , can i use same scripts to deploy on azure , do i need to change anything here .
// Serve static assets if in production
if (process.env.NODE_ENV === "production") {
// Set static folder
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
and this is what i have in my server.js as a starting point. i don't have any config folder to diff environments.for an example
// i don't have this folder structure and am not using webpack
-- config
|-- dev.json
|-- prod.json
can some one suggest , what is the best way to deploy it , or can i use same post-build script by changing it key like azure-postbuild
edited : i think i should use postinstall instead of heroku-postbuild
I have a java back-end that support all of the calls from the UI.
For the UI Phase i'm using nodeJS in order to run it and check that everything is working at localhost:4200, when need to publish it to the tomcat server, copying the dist folder to the webapp at tomcat then the application is available at localhost:8080.
The questions is if there is a simple and easy way while running the UI side on nodeJS to mock all of the response to the ajax call that been made in the UI and when publishing the dist folder to the tomcat it will be transperant and will work with the server side.
I think that its kind of setting up an additional server in nodeJS and map all of the calls and return the static json from there. or there is any other easy way?
"scripts": {
"start": "start npm run start-server && gulp serve",
"start-server": "node src/server/app.js",
"start-client": "ng serve",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update",
"e2e": "protractor"
},
"devDependencies": {
"express": "^4.14.0"
}
create server.js file in project folder and add below code
var express = require("express");
var app = express();
var router = require('express').Router();
var data = require('./server/api/users/data.json');
app.get("/", function(req, res) {
res.send(data)
});
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Listening on " + port);
});
Create a folder for mock data naming server->api->users->data.json and put the below data
[{
"name":"Hello"
},
{
"name":"World"
}]
In order to use mock data, you need to install express server. Add above lines in your package.json and run command npm install and once install, use npm start. npm start will start your gulp serve(or use appropriate cmd as per server installed) and express server both.