Skip to content

ExpressJS - Hello World

With your development environment set up, it’s time to build your first Express application. This classic “Hello World” example will demonstrate the fundamental concepts of creating a web server with Express.

In your project directory (hello-world), create a new file named index.js. This will be the entry point of your application.

// 1. Import the Express library
import express from 'express';
// 2. Create an instance of an Express application
const app = express();
// 3. Define the port number. Use an environment variable or default to 3000
const PORT = process.env.PORT || 3000;
// 4. Define a route for the root URL ('/')
// This handles GET requests to the home page
app.get('/', (req, res) => {
// 5. Send a response to the client
res.send('Hello, Modern World!');
});
// 6. Start the server and listen for incoming connections
app.listen(PORT, () => {
console.log(`Server is running and listening on http://localhost:${PORT}`);
});

Code Breakdown & Modern Practices:

  • import express from 'express': We use the modern ES Module syntax to import packages. To enable this, add "type": "module" to your package.json file.
  • const app = express(): We use const because the app variable will not be reassigned.
  • const PORT = process.env.PORT || 3000: This is a crucial best practice. It allows the port to be set by the deployment environment (like Heroku or Docker), falling back to 3000 for local development. This avoids hardcoding configuration values.
  • app.get('/', (req, res) => { ... }): We use an arrow function for the callback, which is a concise modern syntax.

Save the file and run your server from the terminal using the dev script we set up earlier:

npm run dev

You should see the message Server is running and listening on http://localhost:3000. Now, open your web browser and navigate to http://localhost:3000. You will see the text “Hello, Modern World!”.

Because you are using nodemon, you can now change the response message in index.js, for example, to res.send('Welcome to Express.js!'). When you save the file, nodemon will automatically restart the server. Just refresh your browser to see the updated message.

Let’s dissect the core Express concepts in this simple application.

Routing determines how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).

Our code app.get('/', ...) tells Express: “When you receive a GET request for the root path (/), execute this callback function.”

The callback function always receives two main arguments:

  • req (Request): An object containing information about the incoming HTTP request, such as headers, query parameters, and the request body.
  • res (Response): An object used to send a response back to the client.

The res.send() function sends the HTTP response. Express is smart about it; it can send strings, JSON objects, arrays, or Buffers. It also automatically sets the Content-Type header for you (e.g., text/html for a string, application/json for an object).

Starting the Server: app.listen(port, callback)

Section titled “Starting the Server: app.listen(port, callback)”

This function binds the application to a port on the machine and starts the server to listen for connections. Once the server is ready, the optional callback function is executed—in our case, logging a confirmation message to the console.

  • Separate Routes: For larger applications, you should move your routes into separate files to keep index.js clean. You can use express.Router for this.
  • Middleware: Explore middleware functions, which are functions that have access to the req and res objects and can execute code, make changes, or end the request-response cycle. They are the backbone of any Express app.
  • Error Handling: Implement a centralized error handler to catch and process any errors that occur in your application gracefully.