0
0
NextJSframework~30 mins

Why API routes serve backend logic in NextJS - See It in Action

Choose your learning style9 modes available
Why API routes serve backend logic
📖 Scenario: You are building a simple Next.js app that needs to fetch data securely from a backend. Instead of putting all logic in the frontend, you will create an API route to handle backend tasks like data fetching and processing.
🎯 Goal: Build a Next.js API route that returns a JSON response with a greeting message. Then, configure a frontend page to call this API route and display the message.
📋 What You'll Learn
Create an API route file in the app/api/greet/route.js path
Write a GET handler function that returns a JSON object with a message key
Create a frontend React component that fetches data from the API route using fetch
Display the fetched message inside the component
💡 Why This Matters
🌍 Real World
API routes are used in real apps to handle backend tasks like authentication, database queries, and secure data fetching.
💼 Career
Understanding API routes is essential for full-stack Next.js developers to build secure and scalable web applications.
Progress0 / 4 steps
1
Create the API route file with a GET handler
Create a file at app/api/greet/route.js and export an async function called GET that returns a JSON response with { message: 'Hello from API' }.
NextJS
Need a hint?

Use the Next.js API route pattern with an exported async GET function that returns a Response object containing JSON.

2
Create a frontend React component to fetch from the API
In app/page.js, add 'use client' directive and create a React functional component called HomePage. Inside it, create a state variable message initialized to an empty string. Use useEffect to fetch from /api/greet and update message with the JSON message value.
NextJS
Need a hint?

Add 'use client' at the top since you're using client-side hooks. Use useState to hold the message and useEffect to fetch the API once when the component loads.

3
Add error handling in the fetch logic
Inside the fetchMessage async function in HomePage, add a try-catch block to catch fetch errors. If an error occurs, set message to 'Failed to load message'.
NextJS
Need a hint?

Wrap the fetch call in try and catch. In catch, update the message state with an error string.

4
Add semantic HTML and accessibility features
In the HomePage component, wrap the content inside a <main> element with aria-live="polite" attribute for screen readers. Also, add a <header> with a heading <h1> that says 'Welcome to the Greeting App' above the message. Change the message to a <p> tag.
NextJS
Need a hint?

Use semantic tags like <header> and <main>. Add aria-live="polite" to <main> so screen readers announce message changes.