Introduction to Express.js
By Syncfusion®, Inc. · Last updated
What Express.js is and why it was created, its history and features, Express versus the Node.js http module, Express 4 versus Express 5, how a request flows through an app, what you can build, and how to set up, configure, run and test your first Express 5 server.
What you will learn
- Explain what Express.js is and why developers use it
- Compare Express with the Node.js http module and Express 4 with Express 5
- Set up an Express 5 project with npm, ES modules and npm scripts
- Read the port from environment variables with --env-file or dotenv
- Write, run, test and restart a first Express server
Express.js Introduction
Express.js = a small framework that helps you build web servers with Node.js.
- A web server is a program that waits for requests and sends back answers.
- Node.js lets JavaScript run on a computer, outside the browser.
- Express sits on top of Node.js and does the boring server work for you.
- You write short rules like "when someone asks for
/menu, send the menu". - Most people just call it Express.
Simple lesson: Express helps you write a web server in JavaScript with very little code.
A Real-World Example
Your school canteen gets a new app. Students open it on their phones.
- A student taps Menu. The phone sends a request to the canteen server.
- The server is written with Express.
- Express finds the rule for
/menuand runs it. - The rule sends back the list: Idli, Dosa, Vada.
- The phone shows the list. All of this takes a few milliseconds.
Animation: a phone sends GET /menu to an Express server, and the server sends the menu back
Canteen app Client (phone)
Express on Node.js app.get("/menu") Server
GET /menu
Idli, Dosa, Vada
1. Request 2. Response
The phone asks. Express finds the matching rule and answers.
In this lesson, you will learn:
- What Express is, why it was made and what it can build.
- How Express compares with plain Node.js and with Express 4.
- How a request travels through an Express app.
- How to set up a project and keep secrets out of your code.
- How to write, run, test and fix your first server.
Before You Start
Check these before you go on. You will learn faster if you already know them:
- JavaScript basics: variables, functions, arrays and objects.
- Arrow functions:
(req, res) => ...is used everywhere. - Modules:
importandexportbetween files. - Promises, async and await: for work that takes time, such as a database.
- Node.js basics: running a file with
node file.js. - npm basics: installing packages with
npm install. - HTTP basics: requests and responses. The next lesson teaches these.
- Node.js 18 or later: Express 5 needs it. The current LTS version is best.
Simple lesson: Know modern JavaScript and a little Node.js, and you are ready.
Your First Express Server
Here is a complete Express server. It has just three steps: create the app, add a route, and start listening on a port.
Prefer TypeScript? Choose TypeScript in the Language menu in the top bar. Your choice applies to every lab and exercise in this course. TypeScript labs run with npx tsx. The lesson Express with TypeScript explains the extra parts.
Press ▶ Run. Then look at the panel on the right.
- Terminal shows the start command (
$ node server.js) and the message fromconsole.log. - Response shows
200 OKand the welcome text. - Press the GET /hello button. You get
404 Not Found, because there is no rule for/hello.
In this lab, a small copy of Node.js and Express 5 runs inside your browser. On your own computer, the same code runs with real Node.js. The Download button gives you the project as a zip.
Simple lesson: app.get adds a rule, and app.listen starts the server.
Why Express Was Created
Node.js can already make a web server. So why do we need Express?
- Plain Node.js gives you the request as raw text and numbers.
- You must check the URL yourself with many
ifstatements. - You must set every header, such as the content type, by hand.
- You must read the request body piece by piece.
- Every project ends up writing the same helper code again.
- Express puts these helpers in one small, shared package.
Simple lesson: Express removes the repeated work, so you can focus on what your app does.
History of Express.js
- 2010: TJ Holowaychuk released Express. It was inspired by Sinatra, a small Ruby framework.
- 2014: The company StrongLoop took care of the project.
- 2015 to 2016: IBM bought StrongLoop, and Express moved to the Node.js Foundation.
- Today: Express belongs to the OpenJS Foundation and is looked after by volunteers.
- 2024: Express 5.0 came out, the first big update in about ten years.
- 2025: Express 5.1 became the default version that
npm install expressgives you.
Simple lesson: Express is old, stable and still updated. This course uses Express 5.
Features of Express.js
- Routing: match a method and a path, such as
GET /menu, to your code. - Middleware: small functions that run one after another on every request.
- Request helpers: read the path, query and headers easily with
req. - Response helpers: send text, JSON, files and status codes with
res. - Body parsing: turn sent JSON or form data into a JavaScript object.
- Static files: serve images, CSS and HTML from a folder.
- Templates: build HTML pages from data with a view engine.
- Huge ecosystem: thousands of ready-made packages work with Express.
Simple lesson: Express gives you the basic tools. You add more only when you need them.
Minimal and Unopinionated
Think about two ways to eat at a canteen.
- A fixed thali comes with every dish already chosen.
- A plain dosa counter gives you a dosa, and you pick your own chutneys.
- The thali is quick to start, but hard to change.
- The dosa counter takes a few choices, but you get exactly what you like.
Express is the dosa counter.
Minimal
Minimal = Express ships with only the core pieces.
- No database tool is built in.
- No login system is built in.
- No fixed folder layout is built in.
- The package stays small and easy to learn.
Unopinionated
Unopinionated = Express does not force one "right way".
- You choose the database, such as PostgreSQL or MongoDB.
- You choose the folder layout.
- You choose the validation and login packages.
- The downside: you must make these choices yourself.
Simple lesson: Express gives you a small base and lets you choose the rest.
Express.js vs Node.js
People often mix these two up. They are not the same kind of thing.
- Node.js = the runtime. It runs JavaScript on a computer.
- Express = a package. It runs inside Node.js.
- You install Node.js once on your computer.
- You install Express into each project with npm.
- Express cannot run without Node.js. Node.js runs fine without Express.
Layers: your code on top of Express, on top of Node.js, on top of the computer
Your code: routes like app.get("/menu")
Express: routing, middleware, req and res helpers
Node.js: runs JavaScript, http module, files
Your computer or a cloud server
Each layer stands on the one below it.
Simple lesson: Node.js runs your program. Express is a helper package inside it.
Express.js vs the Node.js HTTP Module
The best way to see the difference is to build the same server twice.
Both servers answer / with a welcome and /menu with a list.
The Plain Node.js Way
This version uses the built-in node:http module only.
Run it and press all three buttons.
/and/menuwork./menu?veg=truegives 404, becausereq.urlis the whole text/menu?veg=true.- To fix it, you would have to split the URL yourself.
The Express Way
Run it and press all three buttons.
- All three work, including
/menu?veg=true. - Express matches the path only, and keeps the query separately.
res.sendsaw an array, so it sent JSON and set the content type for you.- The 404 page for unknown paths comes free.
Side by Side
| Job | Node.js http module | Express |
|---|---|---|
| Match a URL | Many if checks on req.url | app.get("/menu", ...) |
| Query string | Split the URL yourself | Ready in req.query |
| Send JSON | JSON.stringify and set the header | res.send(data) or res.json(data) |
| Unknown paths | Write your own 404 branch | Automatic 404 |
| Request body | Read it in chunks | One line: express.json() |
Simple lesson: Express is built on the http module. It just does the repeated work for you.
Express 4 vs Express 5
Express 5 is the current version. Many older tutorials still show Express 4.
- You do not need to learn this whole table now. Later lessons teach each row.
- For now, remember two things: copy paths from old code carefully, and check your Node.js version.
| Topic | Express 4 | Express 5 |
|---|---|---|
| Node.js version | Very old versions work | Node.js 18 or later |
Errors in async handlers | Lost unless you call next(err) | Sent to the error handler for you |
| Match any path | "*" | A named wildcard, such as "/*splat" |
| Optional part of a path | "/:id?" | Curly braces, such as "/{:id}" |
app.listen callback | Gets no error | Gets the error, if the port is busy |
req.query | Can be replaced | Read-only |
| Removed old methods | req.param(), res.redirect("back") work | They are gone |
You can see one change right now. Run the lab below.
- The server stops with
TypeError: Unexpected ?. - Change
"/menu/:id?"to"/menu{/:id}"and press Run again. - Now both
/menuand/menu/2work.
Simple lesson: Learn Express 5 syntax. When you copy old code, check its paths first.
How an Express App Works
Every request goes on the same short trip through your app.
- Request: a client sends a method and a path, such as
GET /menu. - Middleware: helper functions run first, in the order you added them.
- Route matching: Express looks for a rule with the same method and path.
- Route handler: the matching function runs your code.
- Response: the handler sends an answer with
res.sendorres.json. - Done: the trip ends. No match means a 404 answer.
Animation: a request passes through middleware, route matching and the handler, then a response goes back
Request
Middleware
Route matching
Handler
Response
1. GET /menu arrives 2. Middleware runs first 3. Express finds the GET /menu rule 4. Your handler runs 5. The answer goes back to the client
One request, one trip, one response.
You will learn each step in detail later in this course.
Simple lesson: A request goes in, passes through your functions, and exactly one response comes out.
What You Can Build with Express
- Web applications: full websites with pages and forms.
- REST APIs: send JSON data to apps, such as the canteen menu.
- Backend services: do work for other programs, such as sending emails.
- Server-rendered websites: build HTML pages on the server.
- Login services: check passwords and keep users signed in.
- File upload services: accept photos and documents.
- Mobile app backends: give Android and iPhone apps their data.
- Single-page app backends: serve a React or Vue app and its API.
- Microservices: many small servers, each doing one job.
Simple lesson: If it talks over HTTP, you can probably build it with Express.
Setting Up an Express Project
Open a terminal in the folder where you keep your projects. Run these one by one.
mkdir canteen-api
cd canteen-api
npm init -y
npm install express
npm list express
What each command does:
mkdir canteen-apimakes a new project folder.cd canteen-apimoves into it.npm init -ycreatespackage.jsonwith default answers.npm install expressdownloads Express intonode_modules.npm list expressprints the version. It should start withexpress@5.
Turn On ES Modules
Open package.json. Add "type": "module" and two scripts.
{
"name": "canteen-api",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "node --watch server.js",
"start": "node server.js"
},
"dependencies": {
"express": "^5.1.0"
}
}
"type": "module"lets you useimportandexportin.jsfiles.npm run devstarts the server and restarts it every time you save a file.npm startstarts the server once. Real servers in the cloud use this one.
Easy way to remember: install once (npm install), dev while you code (npm run dev), Ctrl + C to stop.
Simple lesson: npm init, npm install express, then add "type": "module".
Splitting app.js and server.js
Real projects keep two small files instead of one.
- app.js = builds the app: the routes and settings. It does not start anything.
- server.js = starts the app with
app.listen. - Tests can import
app.jswithout starting a real server. - Later, you can start the same app in different ways.
- The terminal runs
npm start, which runsnode server.js. server.jsimports the app from./app.js. Note the.jsat the end.- Node.js needs the full file name when you use
import.
Simple lesson: app.js describes the app. server.js switches it on.
Environment Configuration
Some values change from computer to computer, such as the port or a database password.
- Do not type these values into your code.
- Keep them in environment variables instead.
- Environment variable = a named value the computer gives your program.
- Node.js puts them all in
process.env. - Every value in
process.envis a string, such as"4000".
The .env File
During development, you keep these values in a file named .env.
PORT=4000
CANTEEN_NAME=Green Valley School Canteen
Loading .env
Node.js does not read .env by itself. Pick one of these two ways.
- Node.js 20.6 or later: run
node --env-file=.env server.js. - The dotenv package: run
npm install dotenv, then addimport "dotenv/config";at the top ofserver.js. - Do not use both. Two loaders make it hard to know where a value came from.
- The server listens on 4000, the value from
.env. - Open the
.envtab, changePORTto5000, and press Run again. - Then delete the
PORTline. The server falls back to 3000.
Keeping .env Secret
- Add
.envto your.gitignorefile, so Git never uploads it. - Create
.env.examplewith the same names but no real values. - Teammates copy
.env.exampleto.envand fill in their own values.
# .env.example
PORT=3000
CANTEEN_NAME=
Never push .env to GitHub. Bots scan public code for passwords within minutes.
Simple lesson: Settings live in .env, your code reads them from process.env, and Git never sees .env.
Development Tools
You need a way to send requests to your server while you build it.
- node --watch: restarts the server when you save a file.
npm run devuses it. - Browser: good for quick
GETrequests. Typehttp://localhost:3000/menu. - curl: a terminal command that sends any request. It is built into Windows, macOS and Linux.
- Postman: a popular app for sending and saving requests.
- Bruno: a free, open-source app like Postman. It saves requests as files in your project.
Try these curl commands while your server runs:
curl http://localhost:3000/
curl http://localhost:3000/menu
curl -i http://localhost:3000/hello
curl URLprints the response body.curl -i URLalso prints the status line and headers.
In this course, the Send panel in each lab works like a tiny Postman.
Simple lesson: Use the browser for quick checks and curl, Postman or Bruno for everything else.
Starter Project Files
Your finished starter project looks like this:
canteen-api/
├── node_modules/ packages downloaded by npm (never edit)
├── .env your settings and secrets (never commit)
├── .env.example the same names, no real values (commit this)
├── .gitignore files Git should ignore
├── app.js builds the Express app and its routes
├── package.json name, scripts and packages
├── package-lock.json exact package versions (made by npm)
└── server.js starts the server
The .gitignore file needs only two lines for now:
node_modules
.env
Simple lesson: Five small files are enough to start any Express project.
Your First Express Application, Step by Step
Here is the full app.js and server.js again. Every line is explained below.
The Pieces
- express() = creates the application object, usually called
app. - app.get(path, handler) = adds a route for
GETrequests to that path. - Route handler = the function that runs when the route matches.
- req = the request object.
req.query.namereads?name=Priya. - res = the response object.
res.send()sends text, HTML or JSON. - Port = a door number on the computer. Your server listens at door 3000.
- app.listen(port, callback) = starts the server. The callback runs once it is ready.
Try /greet?name=Priya, then /greet with no name. The || gives a default value.
Stopping and Restarting
- Press Ctrl + C in the terminal to stop the server.
- Run
npm run dev(ornode server.js) to start it again. - With
--watch, saving a file restarts the server for you. - Without
--watch, you must stop and start the server to see changes.
In this lab, ↻ Restart does the same as stopping and starting.
Simple lesson: Create the app, add routes, then listen on a port.
Fixing Common Startup Errors
When a server will not start, the terminal tells you why. Read the first error line.
Press Run. The terminal shows ERR_MODULE_NOT_FOUND.
- The import says
"./app", but the file isapp.js. - Change it to
"./app.js"and run again.
The Errors You Will Meet Most
- Cannot find module './app': add the
.jsending to the import. - Cannot find package 'express': run
npm install expressin the project folder. - Warning: MODULE_TYPELESS_PACKAGE_JSON (older Node.js shows Cannot use import statement outside a module): add
"type": "module"topackage.json. - EADDRINUSE: address already in use :::3000: another server already uses port 3000. Stop it, or pick another port.
- The server starts on the wrong port:
.envwas not loaded. Use--env-file=.envorimport "dotenv/config".
Copy the first error line into your search engine. Someone has almost always met it before.
Simple lesson: Read the first line of the error. It usually names the exact problem.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
import app from "./app" | Node.js adds .js for you | ES modules need the full file name | ERR_MODULE_NOT_FOUND |
No "type": "module" in package.json | import works in every .js file | Node.js must be told the file is a module | Errors or warnings about module type |
Running node server.js outside the project | Node.js finds your project anywhere | Commands run in the current folder | Cannot find module |
Forgetting to load .env | Node.js reads .env by itself | Use --env-file=.env or dotenv | process.env.PORT is undefined |
Committing .env to Git | It is just a settings file | It holds secrets | Passwords leak online |
| Two servers on port 3000 | Many servers can share a port | One port, one server | EADDRINUSE |
Copying Express 4 paths like "*" or "/:id?" | All Express code is the same | Express 5 uses "/*splat" and "{/:id}" | TypeError at startup |
| Editing files and expecting changes | The server reloads by itself | Restart, or use node --watch | You see old answers |
Check Yourself
Exercises
What to Remember
- Express is a small, unopinionated framework for web servers on Node.js.
- It adds routing, middleware and easy
reqandreshelpers to the http module. - This course uses Express 5, which needs Node.js 18 or later and newer path syntax.
- Start a project with
npm init -y,npm install expressand"type": "module". - Read settings from
process.env, load.envone way only, and never commit it. - A first server is three steps:
express(),app.get(...),app.listen(...).
Next: HTTP Fundamentals. You will learn what requests, responses, methods and status codes really are.