Toggle Sidebar   Previous Lesson Complete and Continue  

  Setting up an Express Server in Node.js

The first step is to get an Express REST API application up and running on your local development machine.

In this lecture, we'll learn how to create our first server using Node.js and the Express.js framework. This will allow us to create routes, accept requests, and send back responses.

Navigate to your workspace folder and create a new /twitter directory. This will be the main app folder. Open this folder in VS Code by dragging it to the VS Code icon.

In VS Code, we will use the integrated terminal within this code editor to install some dependencies that we need to start our backend server, but you can also use the terminal provided by your operating system.

The first thing we need to do is create a "package.json" file to provide some metadata about our project.

To do this, run the command "npm init" and fill out the necessary information such as the version, description, entry point etc…

Now that we have a package.json file created, we can install the required NPM package dependencies for our Node server.

To get started, we'll need to add the express, dotenv NPM packages.

Run the command npm i express dotenv to install express and dotenv.

  • Express is a backend web application framework for building RESTful APIs with Node.js. It is designed for building web applications and APIs.
  • Dotenv is a module that loads environment variables from a .env file into the process.env object. This allows us to store configuration separately from our code.

Next, run the command npm i -D nodemon to install nodemon. The "-D" flag means that the package will appear in your devDependencies of the package.json file. We only want to use nodemon in the development process. It will monitor for any changes in your source code and automatically restart the server.

npm i express dotenv
npm i -D nodemon


Now that we have our dependencies installed, we need a way to start the application.

Update your package.json file to include scripts that allow you to run the server in either production or development mode. To run the server in development mode, use the command npm run dev. To run the server in production mode, use the command npm start. This will set the NODE_ENV variable in a env file to "development or production" and run the server.js file.

If you need a refresher, here's an explanation for what each script does:

  • "dev": runs the application when you're in development mode. In this mode, your code will run with special error handling, and other features that make the development process more pleasant. This is the script we'll use to run the application while we're building it.
  • "start": runs the application in production mode. This is how we'll run the application when it's time to deploy to production.

We don't have a "server.js" file yet, so let's create one that will serve as the entry point to the REST API application.

Also, create an "env" file called "config.env", we put it into a folder named: "config" to store your configuration. In the "env" file, include variables for "NODE_ENV" and "PORT". By default, set the "NODE_ENV" variable to "development", PORT variable to "5000" or "3000". Below is a video of the steps above.

In the server.js file, add the following lines of code:

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

// Load env variables
dotenv.config({ path: './config/config.env' });

const app = express();

const PORT = process.env.PORT || 3000;

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

This code starts an express server using the express() function, and stores it in a variable called app.

We load variables from the config.env file and listen on port 3000 for a request. And it's also configured to log a "Server running in development mode on port 3000" message when it first starts.

Save the file then revisit your terminal window and run your application:

npm run dev


You should see our server is running and the console will show the message: "Server running in development mode on port 3000"

Requests

We can now handle requests as shown in the following code:

const app = express(); 

// New code
app.get('/', (req, res) => {
    res.send('Successful response.');
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

These lines of code are where we tell our Express server how to handle a GET request to our server. Express includes similar functions for POSTPUT, etc. using app.post(...)app.put(...), etc.

These functions take two main parameters. The first is the URL for this function to act upon. In this case, we are targeting '/', which is the root of our website: in this case, localhost:3000.

The second parameter is a function with two arguments: req, and resreq represents the request that was sent to the server. We can use this object to read data about what the client is requesting. res represents the response that we will send back to the client.

Here, we are calling a function on res to send back a response: 'Successful response.'.

Open your terminal and run your application:

npm run dev


Then, visit localhost:3000 in your web browser. Your browser window will display: 'Successful response'. Your terminal window will display: 'Example app is listening on port 3000.'.

Middleware

Express allows us to create and use middleware functions, which have the ability to handle all incoming HTTP requests to the server.

These functions can perform a variety of tasks, such as executing code, modifying the request and response objects, ending the request-response cycle, and calling the next middleware function in the stack.

We can create our own middleware functions or use third-party middleware (package) by importing them in the same way we would with any other package.

To create a middleware function, we use the app.use() method and pass it a function. For example, the following is a basic middleware function that prints the current time in the console for every request:

const app = express(); 

// New code
app.use((req, res, next) => {
    console.log(Date.now());
    next();
});

app.get('/', (req, res) => {
    res.send('Successful response.');
});


const PORT = process.env.PORT || 3000;

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

The next() call tells the middleware to go to the next middleware function if there is one. This is important to include at the end of our function - otherwise, the request will get stuck on this middleware.

We can optionally pass a path to the middleware, which will only handle requests to that route. For example:

const app = express(); 

app.use((req, res, next) => {
    console.log(Date.now());
    next();
});

// New code
app.use('/new-request', (req, res, next) => {
    console.log('New request type: ', req.method);
    next();
});

app.get('/', (req, res) => {
    res.send('Successful response.');
});


const PORT = process.env.PORT || 3000;

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

By passing '/new-request' as the first argument to app.use(), this function will only run for requests sent to localhost:3000/new-request.

Run your application again using npm run dev. Then, visit localhost:3000/new-request in your web browser. Your terminal window will display the timestamp of the request and 'New request type:: GET'.

Conclusion

In this lecture, you installed and used Express to build a web server. You also used built-in and third-party middleware functions.

In the next lecture, we will start refactoring and organizing the directories for our Twitter backend application.

Complete and Continue