Introduction to Route Handlers
Veeg om het menu te tonen
So far, you have learned how to build pages and collect user input. However, real applications also need a way to process data on the server.
For example:
- Saving form data;
- Handling requests;
- Working with APIs.
In Next.js, this is done using Route Handlers.
Route Handlers allow you to create backend logic directly inside your Next.js project, without needing a separate server.
Creating a Route Handler
Route Handlers are created inside the app/api/ folder.
Example:
app/
api/
contact/
route.ts
Example: Basic Route Handler
export async function POST(request: Request) {
const data = await request.json();
return Response.json({
message: "Data received",
data,
});
}
This function handles POST requests sent to:
/api/contact
How It Works
When a request is sent to /api/contact, Next.js runs this function on the server.
You can define different handlers based on HTTP methods:
GET: retrieve data;POST: send data;PUT: update data;DELETE: remove data.
Each method is a separate exported function.
Example - GET Handler
export async function GET() {
return Response.json({ message: "Hello from API" });
}
Why Route Handlers Are Useful
Route Handlers allow your app to handle backend logic directly.
This means you can:
- Process form submissions;
- Connect to databases;
- Build APIs;
- Handle authentication logic.
All of this can be done inside the same project.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Introduction to Route Handlers
So far, you have learned how to build pages and collect user input. However, real applications also need a way to process data on the server.
For example:
- Saving form data;
- Handling requests;
- Working with APIs.
In Next.js, this is done using Route Handlers.
Route Handlers allow you to create backend logic directly inside your Next.js project, without needing a separate server.
Creating a Route Handler
Route Handlers are created inside the app/api/ folder.
Example:
app/
api/
contact/
route.ts
Example: Basic Route Handler
export async function POST(request: Request) {
const data = await request.json();
return Response.json({
message: "Data received",
data,
});
}
This function handles POST requests sent to:
/api/contact
How It Works
When a request is sent to /api/contact, Next.js runs this function on the server.
You can define different handlers based on HTTP methods:
GET: retrieve data;POST: send data;PUT: update data;DELETE: remove data.
Each method is a separate exported function.
Example - GET Handler
export async function GET() {
return Response.json({ message: "Hello from API" });
}
Why Route Handlers Are Useful
Route Handlers allow your app to handle backend logic directly.
This means you can:
- Process form submissions;
- Connect to databases;
- Build APIs;
- Handle authentication logic.
All of this can be done inside the same project.
Bedankt voor je feedback!