So you’ve heard of Express.js, the minimalist web framework for Node.js, and you’re ready to build your first backend server. Whether you're working on an API, a web app, or just want to learn backend basics, this blog post will guide you through creating your first Express server—step by step.
Prerequisites
Before we begin, make sure you have:
- Node.js installed (v14+ recommended)
- A code editor (like VS Code)
- Basic knowledge of JavaScript
You can download Node.js from https://nodejs.org
Step 1: Create Your Project Directory
Open your terminal and run:
Or simply create and open that folder in vscode
mkdir my-express-server
cd my-express-server
Initialize a Node.js project:
npm init -y
This will create a package.json
file with default settings.
Step 2: Installing Express
Now, install Express npm package:
npm install express
Step 3: Create Your Server File
Create a file named index.js
:
or just create a new file in vscode using new file option
touch index.js
Step 4: Set Up the Server
In index.js
, add the following code:
const express = require('express'); // requiring express
const app = express(); // create instance of express
const PORT = 3000; // port on which the server will run
// Root route
app.get('/', (req, res) => {
res.send('Hello World! Your Express server is running 🎉');
});
// Start the server
// Listening to any requests that come on the defined PORT
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Step 5: Run Your Server
In the terminal, run:
node index.js
If everything is set up correctly, you'll see:
Server is running at http://localhost:3000
Now open your browser and navigate to http://localhost:3000
. You should see:
Hello World! Your Express server is running 🎉
Bonus: Use Nodemon for Auto-Restarts
Manually restarting the server every time you make a change can get annoying. Install nodemon for convenience:
npm install --save-dev nodemon
Update your package.json
scripts:
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
Now run:
npm run dev
Summary
In this tutorial, you:
- Created a new Node.js project
- Installed Express
- Wrote a basic server
- Tested it in the browser
- (Optionally) used Nodemon for auto-restarts
Further Reading
💡 Start small, build fast, and have fun! Express is powerful but simple. You’ve already taken the first step.
Happy coding! 🙌
Top comments (0)