API routes let your Next.js app run backend code like talking to databases or handling user data. They act like helpers that do tasks behind the scenes.
0
0
Why API routes serve backend logic in NextJS
Introduction
When you need to save or get data from a database without showing it directly on the page.
When you want to handle user login or signup securely.
When you need to process form submissions or send emails.
When you want to keep secret keys safe and not expose them to the browser.
When you want to create a small backend service inside your Next.js app without a separate server.
Syntax
NextJS
export default function handler(req, res) { if (req.method === 'GET') { res.status(200).json({ message: 'Hello from API route!' }) } else { res.status(405).end() // Method Not Allowed } }
API routes are files inside the pages/api folder in Next.js.
The handler function receives req (request) and res (response) objects to handle HTTP methods.
Examples
This example always sends a JSON message when the API route is called.
NextJS
export default function handler(req, res) { res.status(200).json({ message: 'Simple response' }) }
This example only accepts POST requests and sends back the data it received.
NextJS
export default function handler(req, res) { if (req.method === 'POST') { const data = req.body res.status(200).json({ received: data }) } else { res.status(405).end() } }
Sample Program
This API route responds with a friendly greeting when you send a GET request. For other methods, it tells you only GET is allowed.
NextJS
export default function handler(req, res) { if (req.method === 'GET') { res.status(200).json({ greeting: 'Hello from backend!' }) } else { res.status(405).json({ error: 'Only GET allowed' }) } }
OutputSuccess
Important Notes
API routes run only on the server, so you can safely use secrets like API keys here.
Remember to handle different HTTP methods to avoid errors.
You can test API routes by visiting their URL in the browser or using tools like Postman.
Summary
API routes let Next.js apps run backend code inside the same project.
They handle tasks like data fetching, form processing, and secure operations.
API routes use req and res to manage requests and responses.