Discover how API routes can turn your Next.js app into a full-stack powerhouse without extra servers!
Why API routes serve backend logic in NextJS - The Real Reasons
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a website where you have to manually connect your frontend to a separate backend server by writing complex code to handle data fetching, authentication, and business rules.
You must manage different servers, worry about security, and handle errors all by yourself.
This manual setup is slow to build and hard to maintain.
It often leads to bugs, security holes, and slow responses because the frontend and backend are disconnected and require extra work to communicate.
API routes in Next.js let you write backend logic right inside your project.
This means you can handle data, authentication, and other server tasks close to your frontend code, making development faster, safer, and simpler.
fetch('https://external-api.com/data').then(res => res.json()).then(data => console.log(data))fetch('/api/data').then(res => res.json()).then(data => console.log(data))It enables seamless integration of backend logic with your frontend, making your app more efficient and easier to build and maintain.
For example, when a user submits a form, an API route can securely process the data, save it to a database, and return a response without needing a separate backend server.
Manual backend setup is complex and error-prone.
API routes bring backend logic inside your Next.js app.
This simplifies development and improves security and performance.
Practice
Solution
Step 1: Understand the role of API routes
API routes in Next.js let you write backend code inside your project to handle tasks like fetching data or processing forms.Step 2: Identify what backend logic means
Backend logic means code that runs on the server, such as secure operations or database access, which API routes enable.Final Answer:
They allow running server-side code like data fetching and secure operations within the same project. -> Option CQuick Check:
API routes = backend logic handler [OK]
- Thinking API routes style frontend
- Confusing API routes with React components
- Believing API routes generate static pages
Solution
Step 1: Recognize API route syntax
Next.js API routes export a default function that receivesreqandresto handle requests and responses.Step 2: Check each option
export default function handler(req, res) { res.status(200).json({ message: 'Hello' }) } correctly exports a default function withreqandresand sends a JSON response. Others either lack export default or return JSX, which is incorrect for API routes.Final Answer:
export default function handler(req, res) { res.status(200).json({ message: 'Hello' }) } -> Option DQuick Check:
API route = export default function(req, res) [OK]
- Returning JSX instead of JSON
- Not exporting default function
- Missing req and res parameters
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ success: true, data: 'Hello World' })
} else {
res.status(405).json({ error: 'Method Not Allowed' })
}
}Solution
Step 1: Check request method handling
The handler checks if the request method is 'GET'. If yes, it sends a 200 status with JSON containing success and data.Step 2: Determine response for GET request
Since the request is GET, the response will be JSON: {"success":true,"data":"Hello World"} with status 200.Final Answer:
{"success":true,"data":"Hello World"} -> Option BQuick Check:
GET request returns success JSON [OK]
- Assuming all methods return success
- Expecting HTML instead of JSON
- Confusing status codes
export default function handler(req, res) {
if (req.method === 'POST') {
res.json({ message: 'Data received' })
} else {
res.status(405).json({ error: 'Method Not Allowed' })
}
}Solution
Step 1: Review response methods
In Next.js API routes,res.json()sends a JSON response with a default status code of 200, which is correct and functional.Step 2: Check each option
The code properly handles POST withres.json()(200 OK implied) and other methods with 405 error. There are no syntax errors, runtime issues, or missing parameters.res.jsonis the right method for JSON responses.Final Answer:
No error, code is correct -> Option AQuick Check:
res.json defaults to 200, code runs correctly [OK]
- Thinking missing explicit status code is an error
- Confusing res.json and res.send
- Forgetting req or res parameters
Solution
Step 1: Check method and body content
The handler must verify the request method is POST and that the 'email' field exists and is not empty in the request body.Step 2: Validate each option
export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } } correctly checks both conditions and returns a success message with the email. Others either check wrong methods, ignore the email field, or always respond without validation.Final Answer:
export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } } -> Option AQuick Check:
POST + email check = export default function handler(req, res) { if (req.method === 'POST' && req.body.email) { res.status(200).json({ message: `Email ${req.body.email} received` }) } else { res.status(400).json({ error: 'Invalid request' }) } } [OK]
- Not checking request method
- Ignoring required fields in body
- Always returning success without validation
