Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Installation and the first server

To start you need a Node.js project with the express package installed. A server is an ordinary JavaScript file that creates an application and starts listening on a port — the number the browser uses to reach it.

Creating a project

Check your Node.js version — you need 22 or newer — and create a project folder:

node -v
mkdir blog
cd blog
npm init -y
npm install express

npm init -y creates package.json, and npm install express downloads Express into node_modules and records it as a dependency.

Enabling ES modules

Open package.json and add the type field so Node.js understands import and export:

{
  "name": "blog",
  "type": "module",
  "dependencies": {
    "express": "^5.1.0"
  }
}

The other fields created by npm init can stay as they are.

The first server

Create the file src/server.js:

// src/server.js
import express from 'express';
 
const app = express();
const PORT = 3000;
 
app.get('/', (req, res) => {
  res.send('Hello from the blog!');
});
 
app.listen(PORT, (error) => {
  if (error) {
    throw error;
  }
  console.log(`Server started: http://localhost:${PORT}`);
});

express() creates the application, app.get() adds a route for the home page and app.listen() starts the server. If the port is busy, the callback receives an error as its first argument.

Running it

node src/server.js

The terminal shows "Server started: http://localhost:3000". Open that address in the browser and you see "Hello from the blog!". Stop the server with Ctrl+C.

Restarting on changes

Node.js does not notice code changes by itself: after every edit the server has to be restarted. The --watch flag does this automatically:

node --watch src/server.js

It is handy to put both commands into the scripts section of package.json:

{
  "scripts": {
    "dev": "node --watch src/server.js",
    "start": "node src/server.js"
  }
}

Now run npm run dev while developing and npm start on the server.

Common mistake

If you forget "type": "module", Node.js stops with the error Cannot use import statement outside a module. Add the field to package.json — or, in an old project, rename the files to .mjs. This course always uses the type field.

Thanks for reading!

Donate to the site — we work hard for you.