Getting Started with Express.js in 5 minutes

Getting Started with Express.js in 5 minutes

Welcome to my first post in my Express.js series. Today, I am going to show you how to spin up a new express server in a matter of minutes.

Express.js is one of my favorite node frameworks. It is quick and simple while being very flexible. There is a ton of community support and many popular frameworks were built on top of it. You can find plenty of examples of middleware to help with common use cases such as decoration, authentication, error handling, etc. It's a great framework to help build apps quickly and securely. I have built several APIs using express. Let's get started!

TLDR: Here is a working example in my GitHub.

Prereq -- make sure node is installed. If not, you will need to download and install it.

node --version

First, create a folder for the demo.

mkdir express-demo

Next, initialize the new node app.

npm init -y

Then, install express.

npm install express

We will now create the entry point to get an express server started. Either open up your favorite text editor or continue using your terminal (my recommendation). We are going to make a src folder with a file named index.js inside of it.

mkdir src
cd src
nano index.js

Copy in the following text into index.js.

const express = require( "express" );
const app = express();
const port = 8080; // default port to listen

// define a route handler for the default home page
app.get( "/", ( req, res ) => {
    res.send( "Hello world!" );
} );

// start the Express server
app.listen( port, () => {
    console.log( `server started at http://localhost:${ port }` );
} );

(If you are using nano, CTRL + X to exit edit mode. Next, enter Y to "save modified buffer". Finally, hit enter to save with the current file name.)

Lastly, we need to update package.json to instruct npm on how to run your application. We will change main to point to the newly created src/index.js and add a start script.

cd .. 
nano package.json

This is what the changes should look like.

  "main": "src/index.js",
  "scripts": {
    "start": "node .",
    "test": "echo \"Error: no test specified\" && exit 1"

That's it! Express.js is now ready! All you need do to is start it up.

npm run start

You should see the following text.

server started at http://localhost:8080

In a new terminal, you should be able to curl and see "Hello world".

curl localhost:8080

Alternatively, if you navigate to http:localhost:8080 in your favorite web browser you should see "Hello world"!

Here is a working example in my GitHub. I hope you enjoyed this tutorial! You didn't even have to leave your terminal. My next post in this series will teach you how to convert this project to TypeScript. Also, I will be writing about some useful middleware I have written.


Did you find this article valuable?

Support Phillip Ninan by becoming a sponsor. Any amount is appreciated!