Complete the code to define a Next.js API route handler.
export default function handler(req, res) {
if (req.method === '[1]') {
res.status(200).json({ message: 'Hello from API route' });
} else {
res.status(405).end();
}
}The API route checks if the request method is GET to respond properly.
Complete the code to define a server action in Next.js.
import { cookies } from 'next/headers'; export async function [1](formData) { 'use server'; const cookieStore = cookies(); // process formData return { success: true }; }
Server actions in Next.js are exported functions often named action to be used in forms.
Fix the error in the API route to correctly parse JSON body.
export default async function handler(req, res) {
if (req.method === 'POST') {
const data = await req.[1]();
res.status(200).json({ received: data });
} else {
res.status(405).end();
}
}To parse JSON body in Next.js API routes, use await req.json().
Fill both blanks to create a server action that updates cookies and returns a message.
import { cookies } from 'next/headers'; export async function [1](formData) { 'use server'; const cookieStore = [2](); cookieStore.set('user', formData.get('username')); return { message: 'Cookie set' }; }
The server action is named action and uses cookies() to access cookies.
Fill all three blanks to create an API route that handles POST requests and returns JSON.
export default async function handler(req, res) {
if (req.method === '[1]') {
const data = await req.[2]();
res.status(200).json({ message: data.[3] });
} else {
res.status(405).end();
}
}The API route accepts POST requests, parses JSON body with req.json(), and returns the name property from the data.