What Are Route Handlers And Api Routes In Nextjs. What Changed After Next Js V13.2. Node Environment Inbuilt With Nextjs.
- Posted on September 18, 2023
- Technology
- By MmantraTech
- 311 Views
Basic Idea : Routes are URL by which it is decided what page will be opened.
Example : https://mmantratech.com/category/technology
In Next.js, route handlers are functions or modules responsible for defining how a specific route or URL should be managed within your application. Next.js, a popular React framework for building server-rendered React applications, offers a routing system to handle various routes in your application. These route handlers are pivotal in specifying what content should be displayed when a particular URL is accessed.
-1VAy5o8oP7.png)
Best Framework and Full Stack Books - React/Next.js / Node
Overview Route handlers function in Next.js:
1. File-Based Routing: Next.js follows a convention called file-based routing. This means that you can organize your routes by creating files with specific naming conventions within a `pages` directory. Each file corresponds to a route and serves as its associated route handler.
2. Route Handler Functions: In Next.js, a route handler is essentially a React component that you export from a file in the `pages` directory. This component can be either a default export or a named export, and it determines what gets rendered when a user visits a particular route.
3. Dynamic Routes: Next.js also supports dynamic routes, where segments of the URL can vary. Square brackets `[]` are used to create dynamic route segments. For instance, `pages/posts/[slug].js` can handle routes like `/posts/1`, `/posts/2`, etc., and the `slug` parameter can be accessed as a prop in the component.
4. API Routes : Next.js also enables you to create API routes, which are special routes designed to handle server-side logic and respond with JSON data or perform other server-side tasks.
I am not going to deep in this article as my aim to make difference between API ROUTES and ROUTE HANDLERS . So below images are self explanatory where you can understand that in order to create API routes you need to put api folder in pages directory ( this architecture has been before Next.js V13.2 comes as a commercial use).
export default function handler(req,res)
{
if(req.method=="GET")
{
res.status(200).json({ message: 'Get Request' })
}
else if(req.method=="POST")
{
res.status(200).json({ message: 'POST' })
}
}
What Changed in Next.js Version 13.2 and later.
But in Next.js V13.2 everything changed and Routes Handler is shifted to App Directory. Now you can create API Directory to App Folder and route.js file is considered as a default file as page.js is considered special file in App Directory. You must note that when we talk about page.js in App directory that it is for web routes navigating from one page to another page. And when it comes to routes.js we are talking about API routes which is basically Restful APIs
import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://jsonplaceholder.typicode.com/users', {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY,
},
})
const data = await res.json()
return NextResponse.json({ data })
}
How to access body parameters in POST API Handler:
export async function POST(req)
{
const body = await req.json();
const name = body.name;
const email = body.email;
const mobile = body.mobile;
const address = body.address;
const user = await User.create({name,email,mobile,address});
return NextResponse.json({ msg: "User Created Successfully" });
}
Supported HTTP Request :
GET
, HEAD
, POST
, PUT
, DELETE
Conclustion
So, we can say API Routes (pages/api) are replaced by Route Handlers (app/api) in Next.js V13.2.
Route handlers in Next.js simplify the process of building server-rendered React applications with organized and clean routing. They are a foundational element in the development of applications using this framework.
If you really like this article, please share and like it.
Write a Response