Nader's Daily Blog
Welcome to Every Developers favorite blog in the Devosphere

New product features | The latest in technology | The weekly debugging nightmares & more!

Next js 13 Route handlers explained

Next js 13 Route handlers explained

July 25, 2023

Nader Elmahdy

Nader Elmahdy

Take my knowledge and shove it up your brain...

Forget the old api routes, this is the way

Next js

Remember the old API routes that we've been used to for years?

They're no more.

Welcome, to the new Route Handlers.

In Next js 12, if we wanted to check the request type, we'd do something like:

api.ts

1switch (method){
2  case "Get":
3  case "POST":
4    .
5    .
6    .
7}

That was old school, now each request type is a separate function:

Get requests:

route.js

1import { NextResponse } from "next/server";
2export async function GET(request) {
3  return NextResponse.json({message:"Hey"});
4}




POST requests:

route.js

1import Product from "@/app/modules/Product";
2import { mongooseConnect } from "@/lib/mongoose";
3import { NextResponse } from "next/server";
4
5export async function POST(request) {
6  await mongooseConnect();
7  const data = await request.json(); //this is how you get the body data
8  await Product.create(data);
9  return NextResponse.json({ success: true });
10}




PUT requests

route.js

1import Product from "@/app/modules/Product";
2import { mongooseConnect } from "@/lib/mongoose";
3export async function PUT(request) {
4  await mongooseConnect();
5  const data = await request.json();
6  await Product.updateOne({ _id: data._id }, data);
7  return NextResponse.json({ success: true });
8}




Delete request:

route.js

1import Product from "@/app/modules/Product";
2import { mongooseConnect } from "@/lib/mongoose";
3export async function DELETE(request) {
4  await mongooseConnect();
5  if (request.nextUrl?.searchParams?.get("id")) {
6    await Product.deleteOne({ _id: request.nextUrl?.searchParams?.get("id") });
7    return NextResponse.json({ success: true });
8  }
9  return NextResponse.json({ success: false });
10}


Getting the query value

You might've noticed in the delete request above, I'd get the ID value from a query, and use it to delete a specific product, and that's how you get query values:

request.nextUrl?.searchParams?.get("id")

You might also like: