...

How to Set Up a Node.js Project from Scratch: Step-by-Step Guide

A simple, beginner-friendly guide to setting up a Node.js project from scratch. Learn how to initialize a project, run a development server with Nodemon, work with modules, and use popular tools like Express, Joi, and UUID.

How to Set Up a Node.js Project from Scratch: Step-by-Step Guide

If you're new to Node.js and want to quickly get started with creating your own server-side application, this guide is for you. We’ll walk through the complete process of setting up a Node.js projectβ€”from initializing with npm to using Express, UUID, and Joi.

πŸš€ Step 1: Initialize Your Project with NPM

The very first step is to initialize your project using:

npm init

It will ask for project details like name, version, description, entry point, etc. If you want to skip all questions and use default values, run:

npm init -y

πŸ”„ Step 2: Install Nodemon for Development

Nodemon automatically restarts the server when file changes are detected.

Install it as a dev dependency:

npm install nodemon -D


Create a file named index.js in your project root. This will be your server's entry file.

touch index.js


βš™οΈ Step 3: Configure Scripts in package.json

Edit your package.json file to add a custom script for development:

"scripts": {
"dev": "nodemon index.js"
}


Now you can start the development server using:

npm run dev


πŸ“‚ Step 4: Create a Utility Module

You can create a utility file add.js and define a function to export:

function add(a, b) {
return a + b;
}
module.exports = add;


Then, in another file:

const add = require('./add');
console.log(add(5, 9)); // Output: 14


πŸ” Step 5: Export/Import Multiple Methods

You can also export multiple functions from a single module:

function add(a, b) { return a + b; }
function sub(a, b) { return a - b; }
function mul(a, b) { return a * b; }
module.exports = {add,sub,mul};

Then in index.js:

const { add, sub, mul } = require('./add');
console.log(sub(10, 3));


🌐 Step 6: Global Variables in Node.js


Node.js has some useful global variables:

console.log(__dirname); // Path of current directory
console.log(__filename); // Full path of current file


πŸ§ͺ Step 7: Install and Use Express

To build an HTTP server using Express, first install it:

npm install express


Create or update your index.js:

const express = require('express');
const app = express();
const PORT = 3000;

app.listen(PORT, () => console.log(`πŸš€ Server running on http://localhost:${PORT}`));


πŸ“¦ Step 8: Read POST Data with body-parser

To handle POST request data, install:

npm install body-parser

Then use it in your app:

const bodyParser = require('body-parser');
app.use(bodyParser.json());


πŸ†” Step 9: Generate Unique IDs with UUID

Install UUID:

npm install uuid


Usage:

const { v4: uuidv4 } = require('uuid');
console.log(uuidv4());


πŸ“‹ Step 10: Validate Data with Joi

Joi is a powerful schema validator:

npm install joi

Example usage:

const Joi = require('joi');

const schema = Joi.object({
  name: Joi.string().min(3).required(),
  price: Joi.number().required()
});

// Sample object to validate
const data = { name: "Apple", price: 25 };

const { error } = schema.validate(data);
if (error) {
  console.error("❌ Validation Error:", error.details[0].message);
} else {
  console.log("βœ… Data is valid");
}


Final Project Example Code

Here is your full working Node.js Express app:
you need to install the required packages:

npm install express
npm install body-parser
npm install uuid
npm install joi
npm install nodemon --save-dev


πŸ“ File Structure:

project-root/
β”‚
β”œβ”€β”€ index.js
β”œβ”€β”€ add.js
β”œβ”€β”€ package.json


πŸ“œ add.js

function add(a, b) { return a + b; }
function sub(a, b) { return a - b; }
function mul(a, b) { return a * b; }

module.exports = { add, sub, mul };



πŸ“œ index.js

const express = require('express');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
const Joi = require('joi');
const { add, sub, mul } = require('./add');

const app = express();
const PORT = 3000;

app.use(bodyParser.json());

console.log("Addition: ", add(10, 5));     // Output: 15
console.log("Subtraction: ", sub(10, 5)); // Output: 5
console.log("Multiplication: ", mul(10, 5)); // Output: 50
// GET route
app.get('/', (req, res) => {
  res.send('Welcome to your Node.js App!');
});

// POST route with validation
app.post('/product', (req, res) => {
const schema = Joi.object({
  name: Joi.string().min(3).required(),
  price: Joi.number().required()
});

const { error } = schema.validate(req.body);
if (error) {
  return res.status(400).json({ error: error.details[0].message });
}

const product = {
  id: uuidv4(), 
  name: req.body.name,
  price: req.body.price
};

res.status(201).json({ message: "Product added", product });
});

app.listen(PORT, () => {
  console.log(`πŸš€ Server running at http://localhost:${PORT}`);
});



πŸ“œ package.json (scripts part)

"scripts": {
"dev": "nodemon index.js"
}


🧠 You’ve Learned How To:


βœ… Initialize a project
βœ… Create and use utility modules
βœ… Build and run a basic Express app
βœ… Handle POST data
βœ… Generate UUIDs
βœ… Validate input using Joi

Now you're ready to start building scalable and powerful backend applications with Node.js πŸš€! If you'd like, I can help you add MongoDB or routing next.

βœ… Final Thoughts

This guide covered the essential steps to start a Node.js project from scratch and work with modules, validation, and HTTP servers. With this foundation, you're ready to build powerful backend applications!

William Anderson

I am a versatile Full-Stack Web Developer with a strong focus on Laravel, Livewire, Vue.js, and Tailwind CSS. With extensive experience in backend development, I specialize in building scalable, efficient, and high-performance web applications.