Search⌘ K
AI Features

Solution: Building an Express.js Server

Explore how to create an Express.js server integrated with Next.js, focusing on implementing API routes, setting up middleware for error handling, and managing server initialization. This lesson helps you build robust custom servers with proper responses for not found and server error cases.

In this exercise, your objective was to complete the following task:

  • Create an API route named /api/hello that returns a JSON response.

  • Create a middleware to handle server-side errors and respond with a 500 status code and an error message.

  • Implement a middleware to handle 404 errors and respond with a 404 status code and a “Page Not Found” message.

In the next few sections, we’ll review the solution for each task individually.

API routing

Here’s the code for the solution:

JavaScript (JSX)
server.get('/api/hello', (req, res) => {
res.send({ message: 'Hello from the API!' });
});

Let’s break down the code for API routing: ...