Skip to main content
Build your first Express application in minutes. This guide walks you through creating a basic web server with routing, middleware, and static file serving.

Prerequisites

Before you begin, make sure you have:
  • Node.js 18 or higher installed
  • A text editor or IDE
  • Basic knowledge of JavaScript

Create Your First Express App

1

Create a project directory

mkdir myapp
cd myapp
2

Initialize your project

npm init -y
3

Install Express

npm install express
4

Create your server file

Create a file named app.js with this code:
app.js
import express from 'express';

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

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
If using CommonJS instead of ES modules, use const express = require('express');
5

Update package.json for ES modules

Add "type": "module" to your package.json:
package.json
{
  "name": "myapp",
  "version": "1.0.0",
  "type": "module",
  "main": "app.js"
}
6

Start your server

node app.js
Visit http://localhost:3000 in your browser to see “Hello World!”

Add More Routes

Expand your application with additional routes:
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/about', (req, res) => {
  res.send('About page');
});

app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

app.post('/api/data', (req, res) => {
  res.json({ message: 'Data received' });
});

Add Middleware

Parse JSON request bodies and log requests:
import express from 'express';

const app = express();

// Built-in middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Custom middleware
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.post('/api/users', (req, res) => {
  console.log(req.body); // Access parsed JSON body
  res.json({ success: true, data: req.body });
});

Serve Static Files

Serve static files like HTML, CSS, and images:
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();

// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000);
Create a public directory and add an index.html file:
public/index.html
<!DOCTYPE html>
<html>
<head>
  <title>My Express App</title>
</head>
<body>
  <h1>Welcome to Express!</h1>
</body>
</html>

Error Handling

Add basic error handling to your application:
// 404 handler
app.use((req, res, next) => {
  res.status(404).send('Page not found');
});

// Error handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

Using Environment Variables

Create a .env file for configuration:
.env
PORT=3000
NODE_ENV=development
Install and use the dotenv package:
npm install dotenv
import 'dotenv/config';
import express from 'express';

const app = express();
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Complete Working Example

Here’s a complete example combining everything:
app.js
import 'dotenv/config';
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// Logging middleware
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

// Routes
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/api/status', (req, res) => {
  res.json({ status: 'ok', timestamp: Date.now() });
});

app.get('/users/:id', (req, res) => {
  res.json({ userId: req.params.id, name: 'Sample User' });
});

app.post('/api/users', (req, res) => {
  res.status(201).json({ success: true, data: req.body });
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({ error: 'Not found' });
});

// Error handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Internal server error' });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Use nodemon for automatic server restarts during development:
npm install -D nodemon
npx nodemon app.js

Testing Your API

Test your endpoints using curl:
# GET request
curl http://localhost:3000/api/status

# POST request with JSON
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"John","email":"[email protected]"}'

# Route with parameters
curl http://localhost:3000/users/123

Next Steps

Now that you have a working Express application:

Core Concepts

Learn about routing, middleware, and request/response handling

Template Engines

Add dynamic views with EJS, Pug, or Handlebars

Database Integration

Connect to MongoDB, PostgreSQL, or MySQL

API Reference

Explore the complete Express API documentation

Build docs developers (and LLMs) love