0
0
NextJSframework~10 mins

API routes vs server actions decision in NextJS - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a Next.js API route handler.

NextJS
export default function handler(req, res) {
  if (req.method === '[1]') {
    res.status(200).json({ message: 'Hello from API route' });
  } else {
    res.status(405).end();
  }
}
Drag options to blanks, or click blank then click option'
ADELETE
BGET
CPUT
DPOST
Attempts:
3 left
💡 Hint
Common Mistakes
Using POST instead of GET causes the handler to reject the request.
Not checking the method leads to unexpected behavior.
2fill in blank
medium

Complete the code to define a server action in Next.js.

NextJS
import { cookies } from 'next/headers';

export async function [1](formData) {
  'use server';
  const cookieStore = cookies();
  // process formData
  return { success: true };
}
Drag options to blanks, or click blank then click option'
AhandleSubmit
BsubmitForm
Caction
DserverAction
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the function something other than 'action' can cause confusion.
Forgetting 'use server' disables server action behavior.
3fill in blank
hard

Fix the error in the API route to correctly parse JSON body.

NextJS
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();
  }
}
Drag options to blanks, or click blank then click option'
Ajson
Bbody
Ctext
Dparse
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.body directly in Next.js API routes causes undefined errors.
Using req.text() returns raw string, not parsed JSON.
4fill in blank
hard

Fill both blanks to create a server action that updates cookies and returns a message.

NextJS
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' };
}
Drag options to blanks, or click blank then click option'
Aaction
Bcookies
CcookieStore
DsetCookie
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong function names for server actions.
Confusing the cookie store variable with the function to get cookies.
5fill in blank
hard

Fill all three blanks to create an API route that handles POST requests and returns JSON.

NextJS
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();
  }
}
Drag options to blanks, or click blank then click option'
APOST
Bjson
Ctext
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using GET instead of POST in the method check.
Using req.text() instead of req.json() causes parsing errors.
Accessing a wrong property name from the data object.