0
0
NextJSframework~30 mins

HTTP method handlers (GET, POST) in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
HTTP Method Handlers (GET, POST) in Next.js
📖 Scenario: You are building a simple Next.js API route that handles user messages. Users can send a message with a POST request, and retrieve all messages with a GET request.
🎯 Goal: Create a Next.js API route that stores messages in memory. Implement a GET handler to return all messages and a POST handler to add a new message.
📋 What You'll Learn
Create an empty array called messages to store message objects
Create a variable called jsonHeaders with the value { 'Content-Type': 'application/json' }
Write an async GET function that returns all messages as JSON with status 200 and jsonHeaders
Write an async POST function that reads JSON from the request, adds the new message to messages, and returns the added message with status 201 and jsonHeaders
💡 Why This Matters
🌍 Real World
API routes in Next.js are used to build backend endpoints for web apps, handling data fetching and updates.
💼 Career
Understanding HTTP method handlers is essential for full-stack development and building RESTful APIs.
Progress0 / 4 steps
1
Create the messages array
Create an empty array called messages to store message objects.
NextJS
Need a hint?

Use const messages = [] to create an empty array.

2
Add JSON headers configuration
Create a constant called jsonHeaders and set it to { 'Content-Type': 'application/json' }.
NextJS
Need a hint?

Use const jsonHeaders = { 'Content-Type': 'application/json' } to set headers.

3
Implement the GET handler
Write an async function called GET that returns a new Response with the JSON string of messages, status 200, and headers jsonHeaders.
NextJS
Need a hint?

Use new Response(JSON.stringify(messages), { status: 200, headers: jsonHeaders }) to send the messages.

4
Implement the POST handler
Write an async function called POST that reads JSON from the request using await request.json(), pushes the new message to messages, and returns a new Response with the added message as JSON, status 201, and headers jsonHeaders.
NextJS
Need a hint?

Use await request.json() to get the new message, then add it to messages and respond with status 201.