Your First Express Server
8 min read
Your First Express Server
An Express application is created by calling express(). You then attach routes and middleware, and finally start listening for connections with app.listen().
js
import express from "express";
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.send("Hello, Express!");
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});The app.get() call registers a route handler for GET requests to the path "/". The callback receives a Request object and a Response object. Calling res.send() writes the response body and closes the connection.
How app.listen Works
app.listen(port, callback) is a thin wrapper around http.createServer(app).listen(port). The optional callback fires once the socket is bound and the server is ready to accept connections.
Keep your server startup logic in src/index.ts and your Express app creation in a separate src/app.ts. This separation makes the application easier to test without starting a real HTTP server.
Ready to test yourself?
Practice Express— quiz & coding exercises