First Express App

Building your first Express application takes fewer than ten lines of code. This topic walks you through creating a working server step by step, explains what every line does, and shows you how to run and test it in your browser.

Create the Application File

Inside your project folder, create a new file called app.js. Open it in a text editor and add the following code:

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

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

app.listen(3000, function() {
  console.log('Server is running on http://localhost:3000');
});

That is all you need for a working Express server. Now look at each line and understand what it does.

Line-by-Line Breakdown

Line 1: Load Express

const express = require('express');

The require function loads the Express package from your node_modules folder. You assign it to a variable called express. Think of this like plugging in a power tool before you can use it.

Line 2: Create the App Instance

const app = express();

Calling express() creates your actual application object. Every route, middleware, and setting attaches to this app object. It is the central hub of your server.

Lines 4–6: Define a Route

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

This tells Express: "When someone visits the root URL / using a GET request, run this function." The function receives two objects — req (the request, containing information from the browser) and res (the response, which you use to send data back). res.send() sends text back to the browser.

Lines 8–10: Start the Server

app.listen(3000, function() {
  console.log('Server is running on http://localhost:3000');
});

app.listen() starts the server and tells it to watch for incoming connections on port 3000. The callback function runs once the server successfully starts, printing a message to your terminal.

The Request-Response Flow Visualized

Browser types: http://localhost:3000/
       │
       ▼
  [GET request sent to port 3000]
       │
       ▼
  Express checks its routes:
  ┌──────────────────────────────────┐
  │  Route: app.get('/', ...)        │
  │  URL match? '/' === '/' ✓        │
  │  Method match? GET === GET ✓     │
  └──────────────────────────────────┘
       │
       ▼
  res.send('Hello, World!')
       │
       ▼
  Browser displays: Hello, World!

Run the Application

Save your app.js file. Open your terminal, navigate to the project folder, and run:

node app.js

Your terminal prints:

Server is running on http://localhost:3000

Open your web browser and go to http://localhost:3000. The browser displays Hello, World!. Your first Express server is live.

What Localhost Means

The word localhost refers to your own computer. Port 3000 is a communication channel on that computer. Think of your computer as an apartment building, and the port as a specific apartment number. When your server listens on port 3000, it sits in apartment 3000 waiting for visitors.

Your Computer (the building)
│
├── Port 80  → Usually used by web servers in production
├── Port 443 → Usually used for HTTPS
├── Port 3000 → Your Express app (during development)
├── Port 5432 → Often used by PostgreSQL databases
└── Port 27017 → Often used by MongoDB

You can change the port number to anything from 1024 to 65535. Port 3000 is a popular convention for Express development, but it is not required.

Add More Routes

A real application handles multiple URLs. Add more routes to your app.js:

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

app.get('/', function(req, res) {
  res.send('Welcome to the Home Page!');
});

app.get('/about', function(req, res) {
  res.send('This is the About Page!');
});

app.get('/contact', function(req, res) {
  res.send('Contact us at hello@example.com');
});

app.listen(3000, function() {
  console.log('Server running on http://localhost:3000');
});

Stop the running server by pressing Ctrl + C in your terminal. Then restart it with node app.js. Visit these URLs in your browser:

http://localhost:3000/        → Home Page
http://localhost:3000/about   → About Page
http://localhost:3000/contact → Contact Info

What Happens When a Route Does Not Exist

Visit a URL you have not defined, like http://localhost:3000/shop. Express returns a plain text message that says Cannot GET /shop with a 404 status code. This is Express's default behavior for undefined routes. You will learn how to customize this error response in a later topic.

Using Arrow Functions (Modern Syntax)

Modern JavaScript often uses arrow functions instead of the function keyword. Both work identically in Express. The arrow function version looks cleaner:

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

Use whichever syntax feels more readable to you. This course uses arrow functions from this point forward.

Using Nodemon for Auto-Restart

Every time you change your code, you must stop the server with Ctrl + C and restart it with node app.js. Nodemon automates this. If you installed it in the previous topic, use this command instead:

npx nodemon app.js

Nodemon watches your files and restarts the server automatically whenever you save a change. This saves a lot of time during development.

You save app.js → Nodemon detects the change
                → Stops the old server
                → Restarts it automatically
                → Prints "restarting due to changes..."

Add a Script to package.json

Open package.json and add a start script so you can run your server with a short command:

{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  }
}

Now run your server with:

npm start       ← production mode
npm run dev     ← development mode with auto-restart

Summary

A basic Express app requires three steps: load Express with require, create an app instance with express(), and start listening with app.listen(). Define routes using app.get() and send responses with res.send(). Run the app with node app.js and visit http://localhost:3000 in your browser. Add scripts to package.json to simplify your start commands, and use Nodemon during development to skip manual server restarts.

Leave a Comment

Your email address will not be published. Required fields are marked *