Express.js is a minimalist, unopinionated, and extremely flexible web framework with almost 25,000,000 weekly npm downloads. It allows us to quickly and easily set up a web server with Node.js and write our own API code to interact with the back-end technologies of a website.
With this guide, you can have your first Express web server up and running in seven easy steps. Total setup time should take 10 minutes or less.
The only prerequisites for this guide are to have a basic understanding of JavaScript and Node.js. If you do not have Node.js installed on your computer, you can find the instructions for your operating system here.
Step 1: Set Up Your Files
While some projects might have tens or even hundreds of files, our first Express application will only have a few. Inside of our project folder, MyExpressApp, we will have a server.js file to manage incoming requests and an index.html file that will be sent by the server. Two additional files, package.json and package-lock.json, will be generated by npm.
To set up your files using a Bash terminal, enter the following commands:
~$ mkdir MyExpressApp && cd MyExpressApp
~/MyExpressApp$ npm init -y # Will generate JSON files for the project
~/MyExpressApp$ touch server.js index.html
Step 2: Install Express.js Using NPM
Inside of the root project directory, in this case at the top level of MyExpressApp, use npm to install the latest version of Express.
~/MyExpressApp$ npm install Express
# OR, to save keystrokes
~/MyExpressApp$ npm i express
NOTE: Using npm in this manner does not install the package globally. Express is only available for use inside of the MyExpressApp directory.
Step 3: Use server.js to Configure Express
As with any npm package, we need to require it in the server.js file before using it. In addition, we need to run the imported function and configure Express to listen on a specific port on the machine.
Open server.js with favorite text editor and add the following code:
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Listening on port 3000. . .');
});
The identifiers and port number are arbitrary. server is a popular alternative to app (so instead of writing app.listen, some developers write server.listen), and some popular port numbers include 8080 or just 80.
Run the following command from the terminal, inside of the root project folder:
~/MyExpressApp$ node server.js
If all goes well, you will see the message ‘Listening on port 3000. . .’ logged to the console.
Step 4: Define a GET Route for HTTP Requests
Even though our server is now listening on port 3000, if we were to go to localhost:3000 in a browser, nothing would happen because the server isn’t actually responding with anything.
There are many methods we can use to define routes for different URLs and HTTP verbs, but we will start by using app.get. As parameters it takes the route to be defined and the callback function that will run whenever a request is sent to that route.
To send information, the callback function must accept two arguments, typically called req and res. The res object has many methods allowing us to send data back to the user.
app.get('/', (req, res) => {
res.send('WELCOME TO THE HOME PAGE!');
});
This response is in plain text. In the next step we will see how we can send HTML files to the user in the browser.
Step 5: Create an index.html File
Create a folder inside of the root project directory called html and create a file, index.html, inside of it.
~/MyExpressApp$ mkdir html && cd html
~/MyExpressApp/html$ touch index.html
You can enter any code you like in this file, but here is some starter code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Express App</title>
</head>
<body>
<h1>Welcome to the home page!!!</h1>
</body>
</html>
Step 6: Send the HTML File to the User
Back in the index.js file, change the GET route we defined earlier to the following code:
app.get('/', (req, res) => {
res.sendFile('html/index.html', { root: __dirname });
});
Now, when you visit localhost:3000 in the browser, you should see the rendered HTML file sent from the server.
Congratulations! You made your very first server with Express.js. Of course, there is a lot more to Express, topics that we haven’t even begun to consider (for example, how do we serve static assets such as CSS files?), but if you followed this guide then your journey into learning Express is off on the right foot.
One thought on “How to Set Up an Express Server in 7 Easy Steps”