Programming • Updated 8 November 2026

Node.js for Beginners: Install, Modules, npm, Express Server, REST API, Async/Await and Project Structure

Learn Node.js step by step: installing Node, running scripts, modules and npm, async programming, building an Express server and JSON API, environment variables, error handling and next steps for deployment.

Node.jsExpressnpmREST APIJavaScript
⏱ 5 min read

Node.js lets you run JavaScript outside the browser, so you can build web servers, APIs, command-line tools and automation scripts with one language across frontend and backend. It is widely used in Indian startups and agencies. This guide takes you from installation to a working API.

Before you start

You should know basic JavaScript: variables, functions, arrays and objects. If not, read JavaScript basics first.

Install Node.js

  1. Download the LTS (long-term support) version from nodejs.org and install it.
  2. Check versions in a terminal: node -v and npm -v.
  3. Create a project folder and run npm init -y to generate a package.json.

Your first script

// hello.js
const name = "India";
console.log(`Hello, ${name}`);

Run it with node hello.js. Node has no window or document, but offers modules for files, networking and processes.

Modules

// math.js
export function add(a, b) { return a + b; }

// app.js
import { add } from "./math.js";
console.log(add(2, 3));

To use import syntax, set "type": "module" in package.json. The older CommonJS style uses require and module.exports. Built-in modules include fs, path, http and os.

npm packages

npm install express
npm install --save-dev nodemon

npm installs packages into node_modules and records them in package.json. Do not commit node_modules; add it to .gitignore. Use nodemon to restart your server when files change. Be careful with unknown packages, since malicious ones exist. Check download counts, maintainers and recent updates.

Async code

import { readFile } from "node:fs/promises";

async function main() {
  try {
    const text = await readFile("notes.txt", "utf8");
    console.log(text.length);
  } catch (err) {
    console.error("Could not read file:", err.message);
  }
}
main();

Node handles I/O without blocking through an event loop. Use async/await with promises for readable asynchronous code, and avoid heavy CPU work on the main thread.

Build an Express server

import express from "express";
const app = express();
app.use(express.json());

const tasks = [{ id: 1, title: "Learn Node", done: false }];

app.get("/api/tasks", (req, res) => res.json(tasks));

app.post("/api/tasks", (req, res) => {
  const { title } = req.body;
  if (!title) return res.status(400).json({ error: "title required" });
  const task = { id: tasks.length + 1, title, done: false };
  tasks.push(task);
  res.status(201).json(task);
});

app.get("/api/tasks/:id", (req, res) => {
  const task = tasks.find(t => t.id === Number(req.params.id));
  if (!task) return res.status(404).json({ error: "not found" });
  res.json(task);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server on ${PORT}`));

Test with a browser, curl or tools like Postman. Use correct HTTP status codes: 200 for success, 201 for created, 400 for bad input, 404 for not found and 500 for server errors.

Environment variables and config

Store secrets like database passwords and API keys in a .env file loaded with the dotenv package or Node's --env-file flag. Never commit secrets to Git.

Error handling

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
});

Project structure

  • src/routes for route definitions.
  • src/controllers for request logic.
  • src/models or database access.
  • src/middleware for authentication and validation.
  • tests with Jest or the built-in test runner.

Databases and security

  • Use a database such as MongoDB or PostgreSQL. For SQL basics, see SQL guide.
  • Validate input with libraries like zod or joi.
  • Add helmet, rate limiting and CORS settings.
  • Hash passwords with bcrypt and use HTTPS.

Deployment and next steps

Deploy to a VPS, a platform-as-a-service or a container host, using a process manager like PM2. Learn TypeScript with the TypeScript guide and build a frontend with React. Compare backends in the PHP and MySQL guide.

Common Node.js pitfalls

Beginners often forget to handle promise rejections, which can crash a server or leave requests hanging, so wrap awaited calls in try and catch or use a wrapper that forwards errors to the error handler. Blocking the event loop with a heavy loop or synchronous file read makes every request wait, so move CPU-intensive tasks to worker threads or a queue. Confusing the module systems causes errors such as 'Cannot use import statement outside a module', which is fixed by setting the module type or file extension. Hard-coded ports and URLs work locally and fail in production, so read them from the environment. Finally, always pin dependency versions with a lockfile and run npm audit regularly to catch known vulnerabilities.

Practice projects

  • A notes API with create, read, update and delete.
  • A URL shortener that stores links in a JSON file or database.
  • A command-line tool that renames files in bulk.
  • A webhook receiver that logs events to disk.

Testing and tooling

Good habits start early. Use the built-in test runner or Jest to write tests for your route handlers and helper functions, running them on every change. Add ESLint to catch mistakes and Prettier to format code consistently, and configure them in your editor so problems appear as you type. Use Git from day one, commit small changes with clear messages and keep secrets out of the repository. For logging, begin with console output and move to a structured logger when the app grows. Monitor memory and response times in production, and set up automatic restarts. These practices take little time to set up and prevent most of the pain that beginners experience when a prototype becomes a real service.

Frequently asked questions

What is Node.js?

A JavaScript runtime that lets you run JavaScript outside the browser.

What is npm?

The Node package manager, used to install libraries.

What is Express?

A minimal web framework for Node.js.

Is Node.js good for beginners?

Yes, especially if you already know JavaScript.

Which Node version should I install?

The current LTS version.

How do I keep secrets safe?

Use environment variables and never commit them to Git.

Last reviewed 8 November 2026. Rates, limits and rules change, so confirm figures with the official source before you act.

Keep reading

Information on AMTools is for general guidance and is not professional financial, tax, legal or medical advice. Rules, rates and limits change, so check the latest official source before acting.