Next.js Route Handlers | API Routes in Nextjs 13

Поділитися
Вставка
  • Опубліковано 11 гру 2024

КОМЕНТАРІ • 109

  • @saman6199
    @saman6199 Рік тому +7

    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 🔥

  • @karanchilwal1259
    @karanchilwal1259 Рік тому +16

    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  Рік тому +5

      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 :)

  • @bushbuddyplatypus
    @bushbuddyplatypus 9 місяців тому

    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.

  • @fluntimes
    @fluntimes Рік тому

    I've looked around and this is the best video on the new way of using routes in Next. Brilliant

  • @AliMaher212
    @AliMaher212 Рік тому +1

    Thx Dave. Your tutorials makes NextJS docs more easy to understand

  • @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.

  • @markuscwatson
    @markuscwatson Рік тому +4

    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  Рік тому +5

      I may do a video on that after this series covers all of the fundamentals.

    • @0xPanda1
      @0xPanda1 Рік тому +1

      A better alternative would be using drizzle orm

  • @vsakaria
    @vsakaria Рік тому

    Next js doc have updated the example to api dir. Great work Dave

  • @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.

  • @jalalhitech
    @jalalhitech Рік тому

    Thank you so much for the video ❤

  • @ardenttechie
    @ardenttechie Рік тому

    Thank you for the tutorial. I have been searching for this solution for a while now but I can sleep well tonight.

  • @dopetag
    @dopetag Рік тому

    Thank you Dave. It's a really helpful api routes overview!

  • @k303k
    @k303k Рік тому

    Thanks a lot Dave! I 've learned a lot from your series

  • @MOJICA7257
    @MOJICA7257 Рік тому +2

    Thanks Dave!
    Cheers🎉🎉🎉

  • @Shubham-h1z
    @Shubham-h1z Рік тому +1

    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.

  • @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.

  • @FAYZs
    @FAYZs 11 місяців тому

    you are a great instructor . Thank you

  • @jeffery614
    @jeffery614 Рік тому

    Clear and easily understand ! thank you!

  • @sdfsfsfd437
    @sdfsfsfd437 Рік тому +1

    Awesome videos! Many thanks for these Nextjs13 info! 💯💛

  • @7doors847
    @7doors847 Рік тому

    Friday tutssssss! Tu tu tu 🎶 🔥

  • @walassi834
    @walassi834 3 місяці тому

    Hi, @Dave Gray!
    How are you doing?
    I'm loving the next.js content.
    I saw that you have some many courses, but you also had a link to ZTM.
    Do you recommend buying ZTM after seeing you content?

  • @youneshenni5417
    @youneshenni5417 Рік тому

    amazing tutorial. You have a gift for teaching.

  • @Grishopping
    @Grishopping Рік тому

    As always thank you very much Dave for your fantastic videos, regards Jose Grillo

  • @VincentFulco
    @VincentFulco Рік тому

    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"

  • @TravinskiyVladislav
    @TravinskiyVladislav Рік тому

    Thank you, Dave

  • @webncyber
    @webncyber 7 місяців тому

    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!

  • @camembertsucreausucre3440
    @camembertsucreausucre3440 Рік тому

    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  Рік тому +2

      The previous two lessons in this series built small projects. Another coming soon, too.

  • @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?

  • @Mahmoud_A999
    @Mahmoud_A999 11 місяців тому

    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!?

  • @HamidRazaButt
    @HamidRazaButt Рік тому

    Thanks dave for this brilliant work🎉🎉❤

  • @Saad-u5h
    @Saad-u5h Рік тому

    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?

  • @HigherStudyAspirant
    @HigherStudyAspirant Рік тому

    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  Рік тому

      You shouldn't use route handlers for server components. Use them with client components to hide API keys or other secrets.

  • @tunaralyarzada
    @tunaralyarzada Рік тому +2

    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  Рік тому +2

      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.

  • @ruuma1074
    @ruuma1074 Рік тому

    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

  • @peterkawenjakalyemenya8083
    @peterkawenjakalyemenya8083 Рік тому

    thanks dave. however i would like to know how we can impliment both Post and get in the same route.js file

  • @LukeOh-c4e
    @LukeOh-c4e Рік тому

    Goodjob dave:)

  • @abdulrehmanbaber2104
    @abdulrehmanbaber2104 Рік тому +1

    i though async functions cannot be used inside "use client"....?

    • @joaobarradas8894
      @joaobarradas8894 9 місяців тому

      I believe only Route Handlers are allowed (client side calls)

  • @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  Рік тому +1

      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.

  • @koopa9815
    @koopa9815 Рік тому

    THANK YOU!!!!

  • @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.

  • @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

  • @shayanhdry6224
    @shayanhdry6224 Рік тому

    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  Рік тому

      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.

  • @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  Рік тому +2

      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.

  • @patite3103
    @patite3103 Рік тому

    Would it be possible to take the same example but use server actions instead to understand the differences? Thank you in advance!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому

      I do have a video on server actions: ua-cam.com/video/BmUsDuLO598/v-deo.html

    • @patite3103
      @patite3103 Рік тому

      @@DaveGrayTeachesCode the idea is to apply server actions to this example to understand the difference to this video. Thank you.

  • @iamjaivanth4099
    @iamjaivanth4099 Рік тому

    Api route is not working or is not included in build folder, I want to deploy the app, while deploy api are not working

  • @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.

  • @yusifhasanov2504
    @yusifhasanov2504 Рік тому +1

    do you think videos about tRPC

  • @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.

  • @alsherifkhalaf7385
    @alsherifkhalaf7385 Рік тому

    Could you add to this form a simple pdf upload file to another backend ?

  • @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 Рік тому

    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

  • @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 👍

  • @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 ?

  • @erfanpaya3100
    @erfanpaya3100 Рік тому

    Hello. I had a question whether this training is for full stack or frontend.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому +1

      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.

  • @avgspacelover
    @avgspacelover Рік тому

    dave can you make tutorials on designing REST, GRPC AND GRAPHQL API's

  • @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.

  • @Trinita1970
    @Trinita1970 Рік тому

    glorious

  • @eucheckout7
    @eucheckout7 Рік тому

    how can we use express js in next js project??

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому

      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

  • @Drewmssu
    @Drewmssu Рік тому

    crolo

  • @IamAgrocerybag
    @IamAgrocerybag 10 місяців тому

    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...