New product features | The latest in technology | The weekly debugging nightmares & more!
July 25, 2023
Take my knowledge and shove it up your brain...
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:
route.js
1import { NextResponse } from "next/server";
2export async function GET(request) {
3 return NextResponse.json({message:"Hey"});
4}
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}
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}
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}
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")
Next js 13 group routes is a game changer
This is a new feature in next js 13 that solves so many problems
Metadata guide in Next js 13
Next 13 introduced a new way to optimize your metadata, here's what you need to know
All you need to know about useOptimistic hook in Next js13
A new experimental feature from Next js 13 that will greatly imporove your UX
Next js 13 server actions introduction
Who needs api endpoints when we have server actions ?