Next.js 13 API Routes (NEW)
Vložit
- čas přidán 26. 08. 2024
- How to use API Routes inside of App directory of Next.js 13? In this video we will see how to use route handlers which are the replacement for API Routes. Next.js 13 introduced the app directory but it was still missing API Routes, so we needed to use the pages/api folder for defining api routes. With the latest Next.js 13.2 release this is no longer needed and we can define API Routes inside the Next.js 13 app directory.
Learn Programming (Skillshare FREE trial): skl.sh/3cYxUP5
My courses:
React basics: skl.sh/2XAKn7u
HTML & CSS for beginners: skl.sh/34wvGUH
Draft.js basics: skl.sh/3cJ5Hw4
💻 MY GEAR
MY CODIGN LAPTOP: amzn.to/3MI90ci
MY MOUSE: amzn.to/3mr3no9
MY KEYBOARD: amzn.to/3GIoMjh
MY MICROPHONE: amzn.to/3KCDPfv
MICROPHONE BOOSTER: amzn.to/43trLWB
MY MICROPHONE ARM: amzn.to/3oaf5DW
MY CAMERA: amzn.to/3UxyvyJ
MY STREAMING LIGHT: amzn.to/3KE0PuE
Connect with me:
Website: tuomokankaanpa...
My newsletter: tuomokankaanpa...
Twitter: / tumee
Skillshare: www.skillshare...
#nextjs #nextjs13 #vercel
hey tuomo, thank you for this video, very helpful. would be cool if you can go deeper with nextjs13 in general, no rush or stress. also you explain better than everyone i have seen on internet + your english is very understandable your calmness is great.
Thank you for the comment, glad to hear it!
Fantastic! I always get some valuable knowledge from everyone of your videos 👍😁
Thanks that’s great to hear!
Thank you Tuomo! Helped me a lot :)
Great to hear!
How can I now use them in the frontend? Would be the best way to just call a fetch() method on the front end component?
Yeah , u simply fetch basepath/blogposts
Yeah you can use fetch to call them!
@@TuomoKankaanpaa So I'd need to fetch("/api/something") or fetch("localhost:3000/api/something") ? If i fetch("/api/something") it wont work, "Failed to parse URL from /api/something" . It works for fetch("localhost:3000/api/something") but if I deploy it somewhere I'd need to hard-code the deployment address into the code?
This is an awesome Next 13.2 api route tutorial, simple and clear explanation, easy to follow, please dive deeper, thank you 🤩
Glad you liked it! The deep dive is now published on the channel!
I love to watch your tutorials , keep going
Happy to hear that!
can you please make a video for implementing next-auth in app/api which was previously in pages/api, thanks
Good idea!
Thanks for the video explaining API Routes. Please make more video in detail about these API Routes and what else is possible with them.
Thanks for the feedback!
Thanks for the updated info!
Cheers!
great video mate, would love to see more of these.
Cheers!
when will we use this? import { NextResponse } from 'next/server'
Clutch, always timely 🔥
🙌
Will route handlers work with next auth?
Hey, great video. Any idea how we can implement NextAuth with route handlers now?
Havent tried that yet but planning on testing it out!
I've trouble with POST method, when I using POST handler I cannot retrieve the req.body.Is there any solution for next js 13?, I found bodyparser stuff but I don't know where to put it in.
I just published a video where I show how to get the body in POST request!
Can not find any tutorial with real-life app like blog with complete CRUD functionality with these route handlers, apis, etc. Would be very helpful. Thank You!
Thanks for the feedback!
Hello appreciate this, but is there a way to actually read body data when doing a Post request ?(request.body is just a readable stream and can't be used to get useful data)
I am wondering about the same thing
I was able to retrieve the body data (in a very ugly way):
export async function POST(request: NextRequest) {
const body = await request.json()
console.log({ body }.body)
// this is actually a STRING! so do your post with JSON.parse({ body }.body)
// this is how I did it with Mongoose:
await dbConnect()
const createdNote = await Note.create(JSON.parse({ body }.body))
return NextResponse.json(createdNote)
}
I just published a video where I show how to get the body in POST request!
Well done. And, easy to follow
Thanks I’m glad to hear that!
Hey, thanks for the video, btw any ideas how to fix this error with TS? TS2339: Property 'json' does not exist on type '{ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; prototype: Response; error(): Response; redirect(url: string | URL, status?: number | undefined): Response; }'.
Cheers! Not sure about the error, maybe something to do with the object you are calling the .json() with
already implemented in my website. the metadata api is very helpful 👍
Yeah it seems very useful!
@@TuomoKankaanpaa can't wait to see, what next features to be implemented.
how get req.body on post method ?
See my latest video on the channel!
Do you know how to access the request body in the new route handlers? Like if you were posting form data from a page. Seems like it should be the same as the /pages directory, but it doesn't seem to be working.
Looks like it's done this way:
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
const body = await request.json();
console.log({ body });
// do something with the request body
return NextResponse.json({ body });
}
Yes exactly! I just also published a video teaching this and bunch of other stuff you can do with route handlers.
pls, how use Response to do a res.revalidate('/')
Thanks for the feedback!
I am waiting for next video sir ?
It's published!
first always is best
Cheers!
loveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Cheers!
This is so powerful
Indeed!
it is more easier than before ,
I tried to upload file , i thought it its standard web api to use formData ,
but i think the api route handlers parse data or change it :
import { Directus } from '@directus/sdk';
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const formData = await request.formData();
const file = formData.get('file');
formData.append('folder', '887b5198-6b28-4289-8117-87deb4df5e71');
formData.append('file', file as File);
console.log("form data", formData);
const token: string = process.env.DIRECTUS_JOB_TOKEN!;
const url: string = process.env.DIRECTUS_URL!;
const directus = new Directus(url);
await directus.auth.static(token);
const fileResponse = await directus.files.createOne(formData);
return NextResponse.json({ "message": "File Uploaded" });
}
the Axios error :
[AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream]
even if i tried this on client side it works fine :
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
console.log(form)
// this using api route handler
// const response = await fetch('/api/job', {
// method: 'POST',
// body: form,
// })
// console.log(response)
const directus = new Directus('example.com/');
await directus.auth.static('secretkeys');
form.append('folder', '887b5198-6b28-4289-8117-87deb4df5e71');
const file = form.get('file');
if (file instanceof Blob) {
form.append('file', file);
} else {
throw new Error('Invalid file data');
}
const fileRes = directus.files.createOne(form)
.then(async (Response) => {
return await Response?.data.id;
})
.catch(error => {
console.error(error);
});
console.log(fileRes)
};
why is that ? is api route handlers parsing or changing the formData ?