Node.js Tutorial for Beginners
Learn Node.js step by step, from your first script to Express REST APIs, authentication, testing and deployment, with real backend JavaScript examples, output and quizzes for beginners.
Browse all 43 lessons by stage
- Lessons
- 43
- Code examples
- 93
- Exercises
- 143
- Quiz questions
- 161
Node.js course at a glance
Who it's for
Front-end developers who want to build their own back end, beginners who know basic JavaScript, and developers from other languages moving to JavaScript on the server.
Prerequisites
Basic JavaScript: variables, functions, arrays, objects and promises. The JavaScript tutorial covers everything you need.
What you need
Node.js 22 or later (an LTS release), a terminal and a code editor such as VS Code. A few lessons use npm packages such as Express, installed with one command.
How long it takes
About two months for the 25 core lessons at five hours a week, plus a few weeks for the in-depth guides that match your project.
Node.js roadmap: beginner to advanced
Work through the 25 core chapters in the first three stages in order, then use the reference stages to go deeper. Each reference lesson links to its prerequisite and includes examples, practice and a quiz.
Beginner
Running scripts, modules, npm, files, paths, events, process and environment variables, and async patterns.
- 1IntroductionLearn what Node.js is and why it's used for servers and tools, install it, run JavaScript files from the terminal, use the REPL, and understand the event loop that makes Node fast.
- 2ModulesSplit Node.js programs into modules, share code with export and import, understand ES modules versus CommonJS require, use built-in modules with the node: prefix, and get file paths with import.meta.
- 3npm & PackagesManage a Node.js project with npm: create package.json, install and remove packages, separate dependencies from devDependencies, run scripts, understand semantic versioning and the lock file, and use npx.
- 4File SystemRead and write files with the fs/promises API, append to logs, work with JSON files, create and list folders, check whether files exist, handle errors like ENOENT, and know when to use the synchronous and callback versions.
- 5path & osBuild file paths that work on Windows, macOS and Linux with the path module, take paths apart, resolve absolute paths, read system information with os, and work with URLs.
- 6EventsUse Node's event-driven style with EventEmitter: listen with on and once, emit events with data, remove listeners, handle the special error event, extend EventEmitter in your own classes, and await events with once from node:events.
Show all 8 lessonsShow fewer
- 7process & envControl and configure Node.js programs with the process object: read command-line arguments, use environment variables and .env files for settings and secrets, set exit codes, read input, and shut down gracefully.
- 8Async PatternsMaster asynchronous code in Node.js: error-first callbacks, promises, async and await, running tasks in parallel with Promise.all and allSettled, limiting concurrency, timeouts with AbortSignal, and converting callback APIs with promisify.
Intermediate
The http module, Express basics, routing, middleware, REST APIs, validation, templates, error handling and streams.
- 9HTTP ServerBuild a web server with Node's built-in http module: handle requests and send responses, set status codes and headers, route by method and URL, read query strings and JSON bodies, and call other servers with fetch.
- 10Express BasicsBuild web servers faster with Express: install it, create an app, define routes with app.get and app.post, read route and query parameters, parse JSON bodies, and send text, JSON and status codes.
- 11Express RoutingOrganise Express apps with express.Router: split routes into files, mount them on a prefix, chain handlers with router.route, use multiple parameters and router.param, and structure a project so it stays easy to navigate.
- 12MiddlewareUnderstand Express's middleware pipeline: write functions that run before your routes, call next() to continue, attach data to req, stop requests early, apply middleware to the whole app, one router or one route, and use popular packages like cors and helmet.
- 13REST APIDesign and build a complete REST API with Express: resource-based URLs, CRUD with GET, POST, PUT, PATCH and DELETE, correct status codes, pagination, filtering and sorting, consistent JSON responses, and a service layer that keeps routes thin.
- 14ValidationProtect your API from bad data: validate request bodies, route parameters and query strings, return clear 400 errors, describe data with Zod schemas, coerce and default values, and reuse validation as Express middleware.
Show all 9 lessonsShow fewer
- 15Static Files & TemplatesServe websites from Node: deliver HTML, CSS, JavaScript and images with express.static, set caching headers, render dynamic pages from templates with EJS, escape user content safely, handle forms, and know when to choose server rendering or a front-end framework.
- 16Error HandlingHandle errors properly in Node.js apps: throw and catch in async code, create custom error classes with status codes, centralise responses in Express error-handling middleware, add a 404 handler, log useful details without leaking them, and deal with crashes safely.
- 17StreamsProcess data piece by piece with streams: read and write large files without loading them into memory, transform data on the fly, connect streams safely with pipeline, read lines with readline, compress with zlib, and stream HTTP responses.
Advanced
Databases, authentication, security, testing, WebSockets, worker threads, debugging and performance, and deployment.
- 18DatabasesStore data in a real database from Node.js: connect to SQLite with the built-in node:sqlite module, create tables, insert and query with prepared statements, prevent SQL injection, use transactions, wire a database into an Express API, and know where PostgreSQL drivers and ORMs fit.
- 19AuthenticationLet users sign up and sign in securely: hash passwords with scrypt, compare them safely, issue signed tokens or sessions, store them in secure cookies, protect routes with middleware, and understand when to use sessions, JWTs or an identity provider.
- 20SecurityProtect a Node.js API from common attacks: injection, XSS, path traversal, brute force and oversized requests, with security headers, rate limiting, careful CORS, safe secrets handling, dependency audits and the principle of least privilege.
- 21TestingWrite automated tests for Node.js code with the built-in test runner and assert module: unit tests, describe and it, async tests, mocking functions and timers, testing Express APIs end to end, and running tests in watch mode and CI.
- 22WebSocketsBuild real-time features with Node.js: open two-way WebSocket connections with the ws package, send and receive JSON messages, broadcast to every client or a room, detect dropped connections with heartbeats, and use Server-Sent Events for one-way updates.
- 23Processes & WorkersGo beyond a single thread: run other programs with execFile and spawn, move CPU-heavy work to worker threads so the event loop stays responsive, share work across CPU cores with a pool or the cluster module, and pass messages safely.
Show all 8 lessonsShow fewer
- 24Debugging & PerformanceFind and fix problems in Node.js apps: debug with breakpoints using --inspect, log in a structured way, measure timings with performance hooks, spot event-loop blocking, detect memory leaks, profile CPU use, and speed up slow endpoints with caching.
- 25DeploymentTake a Node.js app to production: prepare configuration and scripts, run with NODE_ENV=production, add health checks and graceful shutdown, package it with Docker, deploy to a hosting platform, automate releases with CI/CD, and monitor it once it's live.
Runtime and network references
Buffers and UTF-8, URL parsing, crypto and HMAC, HTTPS and TLS, DNS, TCP framing, compression, timers and microtasks, and fetch with cancellation.
- 26Buffers and UTF-8Understand Node.js Buffer byte lengths, UTF-8 boundaries, shared views, safe allocation, binary fields, and complete encoding exercises.
- 27URL and URLSearchParamsParse URLs safely in Node.js, handle repeated query parameters and encoding, validate origins, and build redirects with complete examples.
- 28Integrity and Webhook HMACVerify raw webhook bytes with Node.js HMAC, validate signature encodings, compare binary digests safely, and distinguish hashing from authentication.
- 29HTTPS and TLS VerificationBuild a local Node.js HTTPS fixture with certificate trust enabled, distinguish hostname checks from CA trust, and avoid disabling TLS verification.
- 30DNS ResolutionDistinguish Node.js operating-system lookup from DNS queries, use an isolated resolver, handle record types and TTLs, and test without public DNS.
- 31TCP Message FramingUse Node.js TCP sockets with length-prefixed messages, handle split and combined chunks, limit frame sizes, and verify a complete local client.
Show all 9 lessonsShow fewer
- 32Compression Formats and HTTPCompare gzip, zlib deflate, and Brotli in Node.js, bound decompression output, and understand HTTP encoding negotiation and cache headers.
- 33Timers and MicrotasksUnderstand Node.js timer thresholds, nextTick and microtask ordering, cooperative yielding, cancellation, and nonoverlapping scheduled work.
- 34Fetch Bodies and CancellationHandle Node.js fetch status errors, one-use response bodies, bounded reads, cancellation, and explicit safe retry policies with local fixtures.
Tools and application boundaries
Readline prompts, package exports, AsyncLocalStorage, web streams, HTTP/2, native TypeScript, the permission model, bounded uploads and diagnostics.
- 35Interactive Readline CLIsBuild sequential Node.js readline prompts, validate answers, handle cancellation and cleanup, and test interactive questions with in-memory streams.
- 36Package Exports and ImportsDefine Node.js package entry points with exports and internal imports, test private subpaths, and understand conditional ESM and CommonJS boundaries.
- 37AsyncLocalStorage Request ContextKeep per-request context across Node.js async calls with AsyncLocalStorage, avoid global state leaks, and test concurrent scopes and callbacks.
- 38Web Streams InteroperabilityConnect Node.js and Web Streams, decode split UTF-8, transform and pipe data, manage locks and cancellation, and understand tee buffering.
- 39HTTP/2 Sessions and StreamsRun a complete local Node.js HTTP/2 client and server, understand sessions and multiplexed streams, and distinguish h2c fixtures from browser TLS setup.
- 40Native TypeScript Type StrippingRun erasable TypeScript directly in Node 24, understand missing type checks and tsconfig support, and retain explicit runtime validation.
Show all 9 lessonsShow fewer
- 41Node Permission ModelRun Node 24 with narrow filesystem grants, inspect permission decisions, distinguish file and directory access, and understand the model limits.
- 42Bounded File UploadsBuild a bounded raw file-upload endpoint in Node.js, generate storage names, clean partial files, and distinguish byte checks from content validation.
- 43Diagnostics Channel InstrumentationPublish optional Node.js diagnostics events with stable payload contracts, handle synchronous subscribers safely, and test subscription cleanup.
What is Node.js?
Node.js lets you run JavaScript outside the browser, on servers and personal computers. It's built on Chrome's fast V8 engine and designed around non-blocking input and output, so a single process can handle thousands of connections at once. That makes it a great fit for web APIs, real-time features such as chat and live dashboards, and command-line tools. Companies of every size use it, and the npm registry gives it the largest package ecosystem of any language.
If you already know some JavaScript from the JavaScript tutorial, Node is the natural next step: the language is the same, and you add files, networks, databases and servers to what it can do.
This tutorial has three stages. The beginner stage covers running scripts, modules, npm, the file system, paths, events, environment variables and asynchronous patterns. The intermediate stage builds web servers, from the built-in http module to Express routing, middleware, a full REST API, validation, templates, error handling and streams. The advanced stage covers databases, authentication, security, testing, WebSockets, worker threads, debugging and performance, and deployment.
Every lesson has examples with their real output, common mistakes, exercises and a quiz. To store data in a document database, continue with the MongoDB tutorial.
How to follow this course
Work through the 25 core lessons in order, because each one builds on the last. After that, the in-depth guides answer the questions real services raise. The runtime and network guides cover Buffer and UTF-8, URLs and query strings, hashing and webhook signatures, HTTPS and TLS, DNS, TCP message framing, compression, timers and the microtask queue, and fetch with cancellation and retries. The tools and application guides cover interactive command-line prompts, package exports, AsyncLocalStorage, web streams, HTTP/2, running TypeScript natively, the permission model, safe file uploads and diagnostics channels. Each guide lists the core lessons to finish first.
What you will learn
10 practical skills, built one lesson at a time
- Run JavaScript with Node and organise code into ES modules
- Manage projects and packages with npm and package.json
- Read and write files, build paths and configure apps with environment variables
- Write clean asynchronous code with promises, async/await and Promise.all
- Build web servers with the http module and Express
- Design REST APIs with routing, middleware, validation and consistent errors
- Store data safely in a database with prepared statements and transactions
- Add authentication and protect apps against common attacks
- Test code and APIs with the built-in test runner
- Add real-time features, use worker threads, profile performance and deploy to production
Practise Node.js your way
Learning sticks when you use it. Pick a mode.
Node.js Exercises
Fill in blanks, predict output and fix broken code with instant feedback.
143 exercisesNode.js Quiz
5, 10 or 20 questions with a timer and explanations after every answer.
161 questionsNode.js Cheat Sheet
Every important piece of syntax on one printable page.
Open cheat sheetLearning Paths
See where Node.js fits in a complete roadmap, and what to learn next.
View learning pathsNode.js FAQ
Do I need to know JavaScript before learning Node.js?
It helps a lot. Node uses the same language as the browser, so you should be comfortable with variables, functions, arrays, objects and ideally promises. If you're new to programming, work through the JavaScript tutorial first, then come back here.
Is Node.js a programming language?
No. Node.js is a runtime: a program that runs JavaScript outside the browser and adds features such as file access and networking. The language is JavaScript (or TypeScript, which compiles to JavaScript).
Should I learn Express or another framework?
Start with Express. It's simple, the most widely used Node framework, and almost every tutorial and job description mentions it. The ideas, such as routes, middleware and request and response objects, carry over directly to Fastify, Koa, Hono and NestJS.
Is Node.js good for back-end development?
Yes. Node is excellent for APIs, real-time apps and services that spend most of their time waiting on databases and networks. For heavy number crunching, you can move work to worker threads or another language, but most web back ends are a great fit.
How long does it take to learn Node.js?
If you already know JavaScript, an hour a day gets most learners through the beginner stage in two weeks and the whole course in two to three months. Building a small project alongside the lessons, such as a to-do API with a database, is the fastest way to make it stick.
Is this Node.js course free?
Yes. All 25 core lessons, the 18 in-depth guides, the exercises, the quiz and the cheat sheet are free, with no account or sign-up needed.
Which Node.js version does the course use?
The examples are written for current long-term support releases, Node.js 22 and later. Lessons point out features that need a recent version, such as native TypeScript type stripping and the permission model.
Should I use CommonJS or ES modules?
New projects should use ES modules (import and export), the JavaScript standard. CommonJS (require) is still common in older code and npm packages, so the course explains both and how they work together.
What should I learn after Node.js?
A database is the natural next step, because most back ends store data. The MongoDB tutorial pairs naturally with Node.js, and the SQL tutorial teaches relational databases such as PostgreSQL.
More tutorials
Python
A friendly first programming language for scripts, data and automation.
Start PythonJava
A reliable, widely used language for apps, Android and big systems.
Start JavaKotlin
The modern language for Android apps, servers and multiplatform code.
Start KotlinSwift
Apple's fast, safe language for iPhone, iPad, Mac and SwiftUI apps.
Start SwiftC#
Microsoft's versatile language for web APIs, games with Unity and desktop apps.
Start C#C++
A fast, powerful language for games, apps and systems software.
Start C++