Next.js Route Handlers | API Routes in Nextjs 13

  Рет қаралды 42,733

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Learn Next.js Route Handlers which replace API Routes in Nextjs 13. With Next.js, it is easy to create GET, POST, and more routes for full stack applications and retrieve the parameters sent with those requests.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Complete Next.js Developer: bit.ly/CompNextJSDev
- Advanced React: bit.ly/AdvReactDev
- Junior to Senior Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
🚩 Subscribe ➜ bit.ly/3nGHmNn
📬 Course Updates ➜ courses.davegray.codes/
❓ Questions - Please post them to my Discord ➜ / discord
☕ Buy Me A Coffee ➜ www.buymeacoffee.com/davegray
👇 Follow Me On Social Media:
Github: github.com/gitdagray
Twitter: / yesdavidgray
LinkedIn: / davidagray
🔗 Source Code: github.com/gitdagray/next-js-...
🔗 Playlist for this Next.js Course: bit.ly/dg-nextjs
Next.js 13 Route Handlers | API Routes in Nextjs
(00:00) Intro
(00:05) Welcome
(00:28) Note on src directory
(01:23) New Route Handlers for API Routes
(02:51) Example API endpoint
(06:06) NextResponse
(07:59) GET Params & echo endpoint
(13:30) Dynamically Evaluated Routes
(14:30) POST Route Handler for a Form
📚 Tutorial References:
🔗 Next.js Official Site: nextjs.org/
🔗 Next.js 13 Beta Docs: beta.nextjs.org/docs
🔗 ES7 React Snippets Extension: marketplace.visualstudio.com/...
Was this Next.js tutorial about Route Handlers for API Routes helpful? If so, please share. Let me know your thoughts in the comments.
#nextjs #route #handlers

Пікірлер: 108
@zombiefacesupreme
@zombiefacesupreme Жыл бұрын
Great video! I was ready to nitpick about whether or not you should put your handlers in a specific folder and you tip toed around that confusion perfectly. The biggest re-factor in this whole thing is change req.body to req.json() on every dang route lol.
@bushbuddyplatypus
@bushbuddyplatypus 4 ай бұрын
A little progress everyday. great advice. I'm coming from Angular and have learnt React and Next over the past few months. It has been tough but getting there one hour at a time.
@saman6199
@saman6199 Жыл бұрын
I've been following this Next JS course in last 8 days and honestly this is the first time I could grasp most of the concept in such a short time, it's all because of your through explanation. You have my gratitude and I really appreciate your effort and hard work Dave 🔥
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad I could help!
@karanchilwal1259
@karanchilwal1259 Жыл бұрын
Hey Dave, I want to express my gratitude for providing such valuable and high-quality videos and explaining topics in a clear and concise manner. I've been following your Next.js series , and I'm wondering how many more videos you plan to release in this series. Thank you for sharing your expertise and knowledge with us!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! I never know how many videos. I just follow the content until I feel like it is complete.
@treyjapan
@treyjapan Жыл бұрын
@@DaveGrayTeachesCode Hello Dave, thank you for creating this immensely useful Next.js series (and of course all of your other coding videos)! I was wondering, with Next.js 13.3 released mere days ago ( adding File-Based Metadata API, Dynamic Open Graph Images, Static Export for App Router, Parallel Routes and Interception), would you consider covering these updates in future videos? That would be super helpful :)
@AliMaher212
@AliMaher212 Жыл бұрын
Thx Dave. Your tutorials makes NextJS docs more easy to understand
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad to hear that!
@k303k
@k303k 6 ай бұрын
Thanks a lot Dave! I 've learned a lot from your series
@dopetag
@dopetag Жыл бұрын
Thank you Dave. It's a really helpful api routes overview!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You are welcome!
@sdfsfsfd437
@sdfsfsfd437 Жыл бұрын
Awesome videos! Many thanks for these Nextjs13 info! 💯💛
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@jeffery614
@jeffery614 9 ай бұрын
Clear and easily understand ! thank you!
@vsakaria
@vsakaria 9 ай бұрын
Next js doc have updated the example to api dir. Great work Dave
@Grishopping
@Grishopping Жыл бұрын
As always thank you very much Dave for your fantastic videos, regards Jose Grillo
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you, Jose!
@FAYZs
@FAYZs 5 ай бұрын
you are a great instructor . Thank you
@youneshenni5417
@youneshenni5417 11 ай бұрын
amazing tutorial. You have a gift for teaching.
@patite3103
@patite3103 Жыл бұрын
Thank you for this series! I would appreciate, if you could some videos on the different new features of version 13.3. Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
13.3 was just released yesterday. I'll be going over some as the series continues.
@jalalhitech
@jalalhitech 8 ай бұрын
Thank you so much for the video ❤
@markuscwatson
@markuscwatson Жыл бұрын
Hey Dave, thanks for this. I’d love it if your next video would show how to store data in a database using something like Prisma. Thanks.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I may do a video on that after this series covers all of the fundamentals.
@0xPanda1
@0xPanda1 Жыл бұрын
A better alternative would be using drizzle orm
@user-wh8py6xb2t
@user-wh8py6xb2t 10 ай бұрын
Hey Dave, you're great, and thanks a lot for providing us such awesome tutorials. I have got a question, what if I want to send files to the API route or backend? In a react app I've done this using new formData() API in the client side, and in the backend to get the formdata I also used multer package. Now, I'm wondering how do I achieve the same thing in the next Js?
@HamidRazaButt
@HamidRazaButt Жыл бұрын
Thanks dave for this brilliant work🎉🎉❤
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@maak8524
@maak8524 Жыл бұрын
Enjoying this Next.js series. Just wanted to mention that the link to the next video in this series that shows up in the final seconds of the video is pointing to 9. Middleware instead of 8. REST API. Caused a little confusion but thought I'd mention it.
@ardenttechie
@ardenttechie Жыл бұрын
Thank you for the tutorial. I have been searching for this solution for a while now but I can sleep well tonight.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad I could help
@arielkashani6390
@arielkashani6390 Жыл бұрын
I realy appreciate you for the way you teach thats very thorough. Could you make a full app with next.js using also cookies and auth?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That might be a good follow-up!
@MOJICA7257
@MOJICA7257 Жыл бұрын
Thanks Dave! Cheers🎉🎉🎉
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Welcome!
@camembertsucreausucre3440
@camembertsucreausucre3440 10 ай бұрын
Hi dave, what a great tutorial, do you know how i can set an api key ?
@annssarr
@annssarr Жыл бұрын
Very good explanation. Better than some paid courses. I want to ask whether you we have some project in nextJS 13.2, if so could you please share the git repo, so me and others can see the which architecture you are using.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The previous two lessons in this series built small projects. Another coming soon, too.
@TravinskiyVladislav
@TravinskiyVladislav Жыл бұрын
Thank you, Dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@stonecomstock
@stonecomstock Жыл бұрын
Thanks Dave! SO being able to create API routes and back end logic with Next, would there still be any need for express JS? Or would I be able to essentially create an entire full stack app all with next JS, and still be able to connect to databases and such with only next? What would be some drawbacks of using only next JS or an example of a situation where I might still want to use express? Thanks again Dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, you can create a full backend REST API with Next.js. It comes down to preference, need, and what you are comfortable with. Next.js is still growing and changing while Express with Node.js is well-established. For example, applying CORS handling in Next requires writing a wrapper function where Express just needs. app.use() and the import of cors.
@7doors847
@7doors847 Жыл бұрын
Friday tutssssss! Tu tu tu 🎶 🔥
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Right on!
@webncyber
@webncyber Ай бұрын
Hi Dave thank you for this great tutorial! I had a general API question to get your input for. I have a headless CMS API and my nextjs calls it to get data, but the way it gets data is by calling the api route in the nextjs, so my library method calls the internal API routes and my internal API calls the CMS API. I wonder if this is a bad design in this case maybe I dont need to use the internal API route and just call the CMS API directly you think? Because I am no able to use cache in this way and it only works with no-store value in fetch method. Please let me know what do you think thank you!
@Mahmoud_A999
@Mahmoud_A999 5 ай бұрын
Your content is very powerful and useful , plz what is vs code theme you use? and can you make a tutorial on prisma and mongodb here!?
@al-doori2392
@al-doori2392 Жыл бұрын
Hello Dave, thanks for the video. I am really looking forward to implementing refresh and access token (JWT) using interceptors like you did in thr React series. I have a project I am working with in NextJs it is real painful I didn’t find any way till now how to implement it with my own backend (c#) and recommendations ?😭
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I may cover auth - or various auth approaches as there is more than one - in a more advanced video after this series covers all of the fundamentals.
@user-td3ts5pc6m
@user-td3ts5pc6m Жыл бұрын
Goodjob dave:)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@VincentFulco
@VincentFulco 6 ай бұрын
Hey Gang- Not sure when it changed, but the api (i.e. echo, etc.) now needs to use the following to get around a #405 error--> "export async function GET" instead of "export default function GET"
@koopa9815
@koopa9815 11 ай бұрын
THANK YOU!!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 ай бұрын
Welcome!
@Waraji258
@Waraji258 Жыл бұрын
Hello Everyone! Thank you much for the video, really good guide!! But I have a question, when you created the Fetch for the API you had to declare the full API URL, localhost:3000/api/... When I deploy my app on Vercel, will I have to change the URL before sending it? But they have a dynamic url for branches. How can i keep track of the BASE URL to update the call for the API ? Before the APP_DIR you just needed to call '/api/example', why the new version needs the full base URL ??
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I used the full URL with thunder client. It is not a component. If the component is part of your app, and you are fetching from the API, then you can just use a path.
@ruuma1074
@ruuma1074 9 ай бұрын
im kinda new with nextJS but I wondering where are the datas goes? because I didnt see any configuration to the database. hopefully isnt a silly question XD
@HigherStudyAspirant
@HigherStudyAspirant 6 ай бұрын
Thanks for detailed explanation. but I have one confusion, what is the need of route handler if we have separate backend suppose nest js. Then calling api endpoints from server component and then from route handler as like same thing calling twice. I am just using next for frontEnd to take advantage of SSR, SEO etc.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 6 ай бұрын
You shouldn't use route handlers for server components. Use them with client components to hide API keys or other secrets.
@peterkawenjakalyemenya8083
@peterkawenjakalyemenya8083 10 ай бұрын
thanks dave. however i would like to know how we can impliment both Post and get in the same route.js file
@DaveGrayTeachesCode
@DaveGrayTeachesCode 10 ай бұрын
The next video in this series does just that.
@alsherifkhalaf7385
@alsherifkhalaf7385 Жыл бұрын
It is great new approach . but i tried to use this new way to upload file via api route , but I failed : just simple file upload : const headers = { 'Content-Type': 'multipart/form-data', }; const response = await fetch('/api/job', { method: 'POST', body: form, headers }) route.tsx : import { NextResponse } from 'next/server'; export const config = { api : { bodyParser : false, } } export async function POST(request: Request) { const res = await request.formData() return NextResponse.json({ res }) } the error : error - DOMException [AbortError]: Error: Multipart: Boundary not found I searched but can't find any solution for use formData through api
@user-ck7ts3ml1g
@user-ck7ts3ml1g 8 ай бұрын
Hi! I got this error when I clicked on Submit in the feedback form - ------------ [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (thank-you, line 0) [Error] WebSocket connection to 'ws://localhost:3000/_next/webpack-hmr' failed: WebSocket is closed due to suspension.. What does it mean and how can I resolve it? Edit - I could see the inputs in the terminal of my VS Code. Though the above problem still persisted.
@avgspacelover
@avgspacelover Жыл бұрын
dave can you make tutorials on designing REST, GRPC AND GRAPHQL API's
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, I want to - good requests!
@alsherifkhalaf7385
@alsherifkhalaf7385 Жыл бұрын
Could you add to this form a simple pdf upload file to another backend ?
@patite3103
@patite3103 Жыл бұрын
Would it be possible to do a tutorial with the same content but using the server actions for the form (version 13.4). Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I'm sure I can in the future.
@shayanhdry6224
@shayanhdry6224 8 ай бұрын
Hello Dave , I want to ask what is the state of ReactJS now ? so there is no more just React JS ? all the react project migrate to Next js ? next question what happens to state management ? with out state management what happens to interactivity of the application ?im not seeing anyone use state management ! Would mind please explaining that ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 8 ай бұрын
Good questions - Next.js is highly recommended. Even by the React docs but there are also other options. You can still write client-side React with Next.js. However, depending on the app, it may be preferred to take advantage of server components, cached requests and database connections.
@EAbdoAhmedSayed
@EAbdoAhmedSayed Жыл бұрын
After react and redux toolkit Is it better to start learning typescript or next ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I recommend TypeScript first although it is not required. Most use TypeScript with Next, and I do in this series.
@patite3103
@patite3103 11 ай бұрын
Would it be possible to take the same example but use server actions instead to understand the differences? Thank you in advance!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 ай бұрын
I do have a video on server actions: kzbin.info/www/bejne/eJ64pHergbRob5o
@patite3103
@patite3103 11 ай бұрын
@@DaveGrayTeachesCode the idea is to apply server actions to this example to understand the difference to this video. Thank you.
@tunaralyarzada
@tunaralyarzada Жыл бұрын
Hey Dave, Thanks for this tutorial at first! But, there is an issue I have been struggling with. The issue is that, when i wanna access to my session obejct information here writing useServerSession(authOption), it returns null! Note that, if i send request through search area of my browser, it return session object. but unfortunately when i send request through my code like axios or fetch, it returns null! Do u know the solution of it?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Definitely not a topic for this series covering the fundamentals. I have many requests for covering auth though and plan to in the future.
@tunaralyarzada
@tunaralyarzada Жыл бұрын
@@DaveGrayTeachesCode I just wanted ur help, it is related to api rootes.
@erfanpaya3100
@erfanpaya3100 Жыл бұрын
Hello. I had a question whether this training is for full stack or frontend.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Please go to lesson 1 in this series and confirm you have completed the prerequisites before starting it. At this point, you should know that Next.js is full stack.
@elemental097
@elemental097 Жыл бұрын
hello, is there a way to get params in route handlers using [items] folder?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You can use params. In the follow up video, I give this a small discussion.
@faf1469
@faf1469 Жыл бұрын
Sir How many more videos left of this amazing nextjs 13 course?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I don't know as I never plan them out. I just follow the content. There's a few left.
@faf1469
@faf1469 Жыл бұрын
@@DaveGrayTeachesCode 👍
@iamjaivanth4099
@iamjaivanth4099 8 ай бұрын
Api route is not working or is not included in build folder, I want to deploy the app, while deploy api are not working
@yusifhasanov2504
@yusifhasanov2504 Жыл бұрын
do you think videos about tRPC
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, I plan to do that.
@abdulrehmanbaber2104
@abdulrehmanbaber2104 8 ай бұрын
i though async functions cannot be used inside "use client"....?
@joaobarradas8894
@joaobarradas8894 3 ай бұрын
I believe only Route Handlers are allowed (client side calls)
@over1498
@over1498 Жыл бұрын
Vercel is on a mission to make as many tutorials as obsolete as possible as quickly as they can. src folder is not even an option anymore (in --experimental-app at least) Can't wait til they deprecate the app folder next week. God help anyone trying to learn the most current version of Next!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
It can feel like that. I do use the src folder with the latest experimental app features. That has not been removed. It is an option while creating the project.
@dopetag
@dopetag Жыл бұрын
Indeed it is an option. And I tend to keep src folder just to keep the things more clear. Another thing is that they don't have a app/api/hello/route.ts for the default setup. I had to create it form scratch.
@kuroisan2698
@kuroisan2698 Жыл бұрын
The most confusing thing I found in the new api directory is the request type isn't http.IncomingMessage instead it is Request so I couldn't find any way to make a file upload since all file parsersI know (formidable, multer, busboy ...) work only with request that has IncomingMessage type do you have any idea to implement file upload ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I'll look into this.
@Trinita1970
@Trinita1970 Жыл бұрын
glorious
@aminbenz
@aminbenz Жыл бұрын
Hey Dave, Any way to catch API route errors globally in Nextjs13? and thnx
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That would be nice - like we do in Node.js - but I am not currently aware of it.
@daviswalker5067
@daviswalker5067 11 ай бұрын
how can we use express js in next js project??
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 ай бұрын
Express is a different framework. If using Express in the backend, I would keep it separate from the Next.js which would only be used in the frontend.
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Жыл бұрын
Is this the end of the course
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Not yet.
@Drewmssu
@Drewmssu 11 ай бұрын
crolo
@IamAgrocerybag
@IamAgrocerybag 4 ай бұрын
Its torture that Next.js added all of this abstraction for getting object data out of a freaking fetch. Furthermore Next docs are unacceptable. Working with Next has been a big L.
@alsherifkhalaf7385
@alsherifkhalaf7385 Жыл бұрын
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 ?
@kiyama24
@kiyama24 Жыл бұрын
Discord id please...
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Link to my Discord server in the description.
@fluntimes
@fluntimes 7 ай бұрын
I've looked around and this is the best video on the new way of using routes in Next. Brilliant
How to Build a REST API with Next.js 13
31:17
Dave Gray
Рет қаралды 94 М.
NextJS Parallel Routes Explained with a Simple Example
14:04
Dave Gray
Рет қаралды 7 М.
Whyyyy? 😭 #shorts by Leisi Crazy
00:16
Leisi Crazy
Рет қаралды 19 МЛН
Please be kind🙏
00:34
ISSEI / いっせい
Рет қаралды 52 МЛН
Native JSON in OTP 27! (Elixir, Erlang, Gleam)
2:03
Code & Stuff
Рет қаралды 1,1 М.
Mastering Next.js Route Handlers: A Comprehensive Guide
43:40
Learn Next.js Parallel Routes In 16 Minutes
16:18
Web Dev Simplified
Рет қаралды 112 М.
NextJS 13 API Routes: Better Than Expected!
15:05
Josh tried coding
Рет қаралды 99 М.
Git MERGE vs REBASE
16:12
Academind
Рет қаралды 1 МЛН
Next.js App Router: Routing, Data Fetching, Caching
14:32
Vercel
Рет қаралды 293 М.
Next.js 14 Tutorial - 31 - Intercepting Routes
10:28
Codevolution
Рет қаралды 30 М.
Whyyyy? 😭 #shorts by Leisi Crazy
00:16
Leisi Crazy
Рет қаралды 19 МЛН