MERN101: Automating Full Stack App with NPM

Say goodbye to the hassle of manually installing and running packages in different directories!

Antonio Caballes
3 min readOct 2, 2023

This tutorial will show you how to automate a full-stack MERN application with NPM.

In MERN projects, usually, there are two directories. One for the server and one for the frontend. Figure 1 gives you a visual representation of this structure.

Figure 1 cliend and server

Problem

The usual process involves navigating back and forth between the mentioned directories (server and frontend).

For example:


# Install packages
cd client
npm install
cd ..
cd server
npm install

# run application and server
cd client
npm start
cd ..
cd server
npm run start

As a developer, this is not a convenient workflow. Our goal is to create a streamline of installation and running of both server and application.

You should have three package.json as shown in Figure 2. One for the frontend, another one for the server and one for both which we will create later.

Figure 2 package.json

Solution

Let’s dive into it. First we need to create our root package.json

Make sure you are in the root directory where your server and frontend folder reside.

npm init -y

You should have the package.json in your root directory just like in Figure 1.

Open your newly generated package.json and under scripts. Let’s create a root watch.

"scripts": {
//...
"watch": "npm run server & npm run client"
//...
}

This watch seamlessly run both the client and the server. But before that, we need to add the “server” and “client” in our root package.json

at this very moment we have nothing to run since there is no server and client in our root package.json.

"scripts": {
// added client and server
"server": "npm run start --prefix server",
"client": "npm start --prefix client",
"watch": "npm run server & npm run client"
}

We’ve now added npm run start — prefix server for the server and npm run start — prefix server for the client.

The scripts added is equivalient to cd client && npm start the same with the server. It is up to you which version you want to use.

Now, the magic happens! Let’s test this setup:

npm run watch

As you press enter, you should see in your terminal the logs. As this is a MERN application, React web application should open right away (Figure 3).

>client
> npm start --prefix client

> nasa-project-api@1.0.0 start
> PORT=8000 nodemon src/server.js
Figure 3 React app compiled successfully

Challenge

Now you configure the npm install with the same concept.

Give it a try and watch your MERN stack project take off smoothly! Happy coding! More MERN dev setup to come!

--

--

Antonio Caballes
Antonio Caballes

Written by Antonio Caballes

I Cybersecurity enthusiast, coder, programmer.

No responses yet