Your First Express Server
Workplace Context
Your team needs to quickly set up a web server to handle incoming web traffic for a new application. Express.js is the chosen tool because it’s lightweight and fast. Your first task is to create a basic server that can respond to requests and serve a simple welcome page.
Learning Objectives
By the end of this lesson, you will be able to:
- Explain the purpose of Express.js.
- Create a simple web server using Express.
- Handle
GET
requests and send back responses. - Serve static HTML files to the browser.
What is Express.js?
Express.js is a minimal and flexible Node.js web application framework. Think of it as a tool that sits on top of Node.js’s built-in http
module, making it much easier to build a web server.
If Node.js is the engine of a car, Express.js is the chassis, steering wheel, and dashboard—it provides the structure and controls that make the engine usable for a specific purpose, like building a web application. Without Express, you would have to write much more code to handle basic tasks like interpreting a URL or organizing your application. Express simplifies this process significantly.
Building and Running Your First Server
An Express application is essentially a JavaScript file where you call functions that define how your server should behave. Let’s build a classic “Hello, World!” server and then break it down line by line.
To get started, you first need to have express
installed in your project using npm install express
.
From there, you can create a file named server.js
and add the following code:
// 1. Import the express library
const express = require('express');
// 2. Create an instance of an Express application
const app = express();
// 3. Define the port the server will run on
const port = 3000;
// 4. Define a route handler for GET requests to the root URL ('/')
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// 5. Start the server and have it listen for incoming connections
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Line-by-Line Breakdown
-
const express = require('express');
This line imports the Express library into our file. Therequire()
function is Node.js’s way of pulling in code from other files or, in this case, from an installed package in ournode_modules
directory. -
const app = express();
Here, we execute the importedexpress
function. This creates anapp
object, which is the main instance of our Express application. Thisapp
object holds all the methods and properties we need to build our server. -
const port = 3000;
This line defines a variable for the port number. A port is like a numbered door on a computer that programs use to communicate over a network. Port 3000 is a common choice for web development, but there’s nothing special about it. We could use 3001, 8080, or many others, as long as they aren’t already in use by another program on our machine. -
app.get('/', (req, res) => { ... });
This is our first route handler. It tells the server what to do when it receives a specific request from a browser or another client. Let’s look at its three parts:app.get
: This is an Express method for handling HTTP GET requests. AGET
request is the most common type; it’s what your browser performs every time you type a URL into the address bar.'/'
: The first argument is the path. A single slash'/'
represents the “root” of your website—the default page you land on, likehttps://www.google.com/
.(req, res) => { ... }
: The second argument is a callback function that runs only when the method and path are matched. We’ll explorereq
andres
more in the next section.
-
app.listen(port, () => { ... });
This line starts the server. Theapp.listen()
method tells our application to “listen” for incoming network requests on the specifiedport
. The second argument is another callback function that runs once the server has successfully started, logging a helpful message to our terminal.
Running the Server
To run this code:
- Save it in a file named
server.js
. - Open your terminal and navigate to the same directory.
- Run the command:
node server.js
. - You should see the message:
Server is running at http://localhost:3000
. Your server is now active! - Open a web browser and go to http://localhost:3000 . You will see the “Hello, World!” message.
Handling Requests (req
) and Responses (res
)
The callback function in our route handler, (req, res) => { ... }
, is the heart of our application’s logic. It receives two crucial objects as arguments:
-
req
(Request): This object contains a wealth of information about the incoming HTTP request. It’s your window into what the client is asking for. It includes properties like:req.url
: The URL path that was requested.req.method
: The HTTP method (e.g., ‘GET’, ‘POST’).req.headers
: The HTTP headers sent by the client.req.params
andreq.query
: Objects containing data from the URL, which we’ll cover in the next lesson.
-
res
(Response): This object is your tool for crafting and sending a response back to the client. We usedres.send()
to send a simple text response, but you have many other powerful methods:res.json()
: Sends a response in JSON format. Essential for building APIs.res.status()
: Sets the HTTP status code (e.g.,res.status(404)
for Not Found).res.sendFile()
: Sends a complete file, which we’ll explore next.
Serving Static Files
A web server’s job isn’t just to send back text. It also needs to provide static assets - files that don’t change - like HTML pages, CSS stylesheets, JavaScript files for the browser, images, and fonts.
To do this, we use a special piece of Express functionality called middleware. We will explore middleware in detail in a future lesson, but for now think of middleware as a helper that can process a request before it reaches our specific route handlers.
express.static()
is a powerful built-in middleware that tells Express to automatically find and send files from a specific directory.
What about path
and __dirname
?
How does Express know where to find the public
directory? The path to it can change depending on where you run your node
command from. To create a reliable, foolproof path, we use two tools:
- The built-in Node.js
path
module. - The
__dirname
variable.__dirname
is a special Node.js variable that always contains the absolute path to the directory where the currently executing script (server.js
) is located.
By using path.join(__dirname, 'public')
, we create a complete, absolute path to the public
folder that will work no matter where you run the server from.
Let’s see it in action. Imagine a project structure like this:
/my-project
├── public/
│ └── index.html
└── server.js
<!DOCTYPE html>
<html lang="en">
<head>
<title>My App</title>
</head>
<body>
<h1>Welcome to my website!</h1>
</body>
</html>
const express = require('express');
const path = require('path'); // Node.js 'path' module
const app = express();
const port = 3000;
// Tell Express to use the 'express.static' middleware
// to serve all files from the 'public' directory.
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Now, when you run this server and go to http://localhost:3000
, Express will look in the public
folder for an index.html
file and serve it automatically.
Activities
Activity 1: “Hello World” Server
- Set up a new project directory.
- Initialize it with
npm init -y
. - Install
express
. - Create a
server.js
file. - Write the code for a basic Express server that responds with “Hello, Express!” on the root route (
/
). - Create additional routes to respond with other information about the server.
- Run the server and test it in your browser.
Activity 2: Serve a Static Homepage
- In the same project, create a
public
directory. - Inside
public
, create anindex.html
file with a simple welcome message and astyles.css
file that changes the background color. - Link the stylesheet in your HTML file.
- Modify your
server.js
to useexpress.static
to serve files from thepublic
directory. - Restart your server and visit
http://localhost:3000
. Your HTML page with its styling should appear.
Knowledge Check
What is the main purpose of the express()
function?
- Select an answer to view feedback.
In an Express route handler (req, res) => {}
, what is the res
object used for?
- Select an answer to view feedback.
What is the function of express.static()
?
- Select an answer to view feedback.
Summary
In this lesson, you learned how to create a basic web server using Express.js. You saw how to handle incoming requests with route handlers and send back responses. You also learned how to serve static files, which is a fundamental requirement for any web application. With these building blocks, you are now ready to create more complex routing and functionality.