How to Build a REST API with Next.js 13

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ธ.ค. 2024

ความคิดเห็น • 132

  • @minimumt3n204
    @minimumt3n204 ปีที่แล้ว +12

    This tutorial is absolutely amazing for people who have no idea how api routes work (me). The way you go in depth explaining things is by far the best I've seen, you make it so easy to understand. Fantastic content!

  • @tinymurky7329
    @tinymurky7329 ปีที่แล้ว +4

    Dynamic Route can also been get like below
    export async function GET ({ params }:{params:{id:string} }) {
    const { id } = params
    }

  • @andreaswu7973
    @andreaswu7973 ปีที่แล้ว +8

    your teaching skills are immense Dave. you're one of the best in the business. always enjoying your series!

  • @socialultra7219
    @socialultra7219 ปีที่แล้ว

    Hi, I just wanted to say a big thank you.
    I've been searching across the internet to find the answer you just gave.
    It's only now I know you can create api routes in the backend (calling external apis) and then call the api routes in the frontend to grab that data. I would have never thought of that, if it wasn't for you.
    Thank you very much.

  • @onelastkiwi8041
    @onelastkiwi8041 10 หลายเดือนก่อน

    this is now my favorite teaching channel

  • @chomok-bd
    @chomok-bd ปีที่แล้ว +3

    Waiting for more from you sir. Hope u will teach Nextjs 13 in depth. Thanks a lot 🎉

  • @mdsalahuddin46464
    @mdsalahuddin46464 ปีที่แล้ว +1

    Best next js tutorial in the youtube

  • @kynjal23
    @kynjal23 ปีที่แล้ว

    i am forever grateful sir, been searching for a teacher that teaches next js

  • @shazeemalichishty7322
    @shazeemalichishty7322 9 หลายเดือนก่อน

    Thanks Dave, i finally get it to work.

  • @travisv6431
    @travisv6431 ปีที่แล้ว

    at 29:47 I was getting a 500 error when I tried to send the request for todo id 199. deleting the JSON body resolved the error.

  • @web3compares
    @web3compares ปีที่แล้ว +2

    Thank you Dave for great content.
    I have one question though. Isn't it better to use below code for getting "id" in "Dynamic Api route" section of your video:
    export async function GET(request: Request, { params }: {
    params: { id: string }
    }) {
    const id= params.id;
    }
    Regards

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      I don't know if it is _better_ but it is another possibility. I have shown that way in previous videos in this series. Now you have an alternative, too! 🚀

    • @web3compares
      @web3compares ปีที่แล้ว

      @@DaveGrayTeachesCode Thanks for the reply.

  • @igbrowns1151
    @igbrowns1151 ปีที่แล้ว +1

    Thanks so much sir🙇. We love❤️ to practice and see more of this

  • @RhysLopez
    @RhysLopez ปีที่แล้ว

    u make it easy to understand 😭thank youu

  • @noahspottdev
    @noahspottdev 7 หลายเดือนก่อน

    Great video - thank you!

  • @justiceessiel6123
    @justiceessiel6123 ปีที่แล้ว +1

    Concerning when and when not to use the page routes . You said the page routes and the generateParams are built at the same and its not advisable to use it . but what if we want to acutallly protected some APi keys and that is why we are using the page routes at build time to fetch the data

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Only a server component uses generate static params. Your API keys are protected in a server component. They stay on the server. No need for a server component to send a request to an API route. Just request the data you need from the server component.

    • @justiceessiel6123
      @justiceessiel6123 ปีที่แล้ว

      @@DaveGrayTeachesCode wow the quickest response . And last one is the generateParams the only way to differentiate the ssr from ssg. I know we use the build to see it but would like to know other strict rule on knowing how to stick to either ssg or ssr

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      @@justiceessiel6123 If the server component just returns JSX and doesn't fetch data or other data retrieval operations, it will be static. If it does fetch data but doesn't use generateStaticParams, it will be SSR. If it does use generateStaticParams, it is usually a dynamic page using SSG.

    • @justiceessiel6123
      @justiceessiel6123 ปีที่แล้ว

      @@DaveGrayTeachesCode you are the best ! Thank you sir

  • @LarryMarkel
    @LarryMarkel ปีที่แล้ว

    Killer video. Cant believe they still havent fixed the DELETE method!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Thank you and I agree!

    • @ImranKhan-wz8hv
      @ImranKhan-wz8hv ปีที่แล้ว

      Ok I got stuck here bc I kept getting an error. I was using Next 13.4.7

  • @k303k
    @k303k ปีที่แล้ว

    Thanks a lot for the series Sir!

  • @azharmahmood624
    @azharmahmood624 ปีที่แล้ว

    Impressed with your teaching skills Dave, really impressive, please keep it up. I hope will learn a lot from you.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Thanks, will do!

    • @azharmahmood624
      @azharmahmood624 ปีที่แล้ว

      @@DaveGrayTeachesCode please make a video on the topic of CURD with (Neon Serverless DB / Postgres DB and Next JS), it is really handy if you can make 2 videos, one CRUD operations with SQL Queries and 2nd one with any ORM like Prisma. It is humble request Please make it ASAP.

  • @alsherifkhalaf7385
    @alsherifkhalaf7385 ปีที่แล้ว

    can I am creating a simple todo app, and I want to make the same nextjs server to serve a react native app using Route handlers to create Restful APIs to handle SQLite database for example ?
    and the concurrent requests, how the NextJS route handlers deal with concurrent requests ?

  • @akosbalint3485
    @akosbalint3485 ปีที่แล้ว +3

    There is a much simpler way to get params from a dynamic route
    export async function GET(
    request: NextRequest,
    { params }: { params: ParamsType }
    ) {
    const { id } = params;

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +4

      I have shown the params way in previous videos concerning dynamic routes if you've been following this series? I suppose I could or should have shown both. Not sure that one is easier / simpler than the other. Now you have an alternative. 😃

    • @h3nry_t122
      @h3nry_t122 ปีที่แล้ว

      the strange thing is that its in the middle of the documentation 😭

  • @Sam_Pila
    @Sam_Pila ปีที่แล้ว

    hello, how to create api endpoint api/product and api/products without create separate folder, so those 2 endpoints are in same folder.
    thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      You could look at using a catch-all route: nextjs.org/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments

  • @shahabulalam8803
    @shahabulalam8803 ปีที่แล้ว

    Very well teaching dave

  • @mywaycoding6413
    @mywaycoding6413 ปีที่แล้ว +1

    Sir thank you 💕 you are really best for me

  • @ofirlevy3682
    @ofirlevy3682 ปีที่แล้ว

    Great video,
    My web app is now using backend in node, so I can transfer all my backend to next js handlers?
    Or its not come to replace node backend service and just it's just helper?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      It is not exactly the same as Node.js and Express. You will probably be interested in my next video on middleware later this week. I'd wait on switching over.

  • @zebrox4416
    @zebrox4416 ปีที่แล้ว +1

    Thanks, sir!
    btw shouldn't we create PUT and DELETE functions inside the dynamic route rather than passing 'id' in the body? I think putting 'id' inside the body when using the DELETE operation instead of using a dynamic route is often discouraged but I am not sure.

  • @davidjohn3740
    @davidjohn3740 ปีที่แล้ว

    I'm struggling to get my head around where to fetch data (content) from a CMS. I set it up with a Route Handler, and fetched it in a server component. Now after watching this I'm thinking I don't need the API. I use an environment variable(secret), but I understood that would still be secure without the API. Is that correct? You're a legend, Dave

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      That is correct. No need for the API route when you can fetch from the server component. Use the API routes for client components - processing forms, hiding URLs, hiding env keys, etc..

  • @AntNZ
    @AntNZ ปีที่แล้ว

    Lookin forward to the middleware video 😊

  • @vinalkumar6934
    @vinalkumar6934 ปีที่แล้ว

    This was really helpful thanks.

  • @juandaniel6726
    @juandaniel6726 ปีที่แล้ว

    Thank you so much Dave!

  • @nami07.03
    @nami07.03 ปีที่แล้ว

    is this not applicable in the latest next version? I tried DELETE method but can't received a message.

  • @AmodeusR
    @AmodeusR ปีที่แล้ว

    In the last section about the Dynamic API Route I missed the explanation to why we were doing that route. It would be nice if you could explain what or why we're doing what we are going to do next time :)

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      I suggest always cross-referencing the docs. I try to make it clear but I can't please everyone.

  • @saswatpranat6748
    @saswatpranat6748 ปีที่แล้ว +1

    Sir is it possible to start side hustle using html and css

  • @GabJornacion
    @GabJornacion ปีที่แล้ว

    Once this is setup, I can still use the same app folder for the front end part of right? and just use the API routes to fetch data and display on FE?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Note what I state in the video about fetching from app API routes - there are times you do not want to and times that you do.

    • @GabJornacion
      @GabJornacion ปีที่แล้ว

      @@DaveGrayTeachesCode Thanks for replying! I probably missed what you said haha. But I appreciate your tutorials nonetheless!

  • @monishbk5612
    @monishbk5612 ปีที่แล้ว

    If we create the rest api using nextjs and after the build if we try to fetch the api after the build and we if update the data from the data base it won't fetch the updated data it reads from the cache how to over come that?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Keep going. The next lesson is all about revalidation.

  • @NOTHING-en2ue
    @NOTHING-en2ue ปีที่แล้ว

    very nice tutorial ❤

  • @patite3103
    @patite3103 ปีที่แล้ว +1

    I've tried with version 13.4.2. I get an error message "SyntaxError: unexpected end of JSON input". Did someone get the same error message by using this version?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      If this is in the DELETE route, I have filed an issue with Next.js: github.com/vercel/next.js/issues/48096
      I see others are still having this issue.
      You can npm i next@13.2.4 to match what I think I have in my package.json for this video. You can check in the course resources.

  • @sonamohialdin3376
    @sonamohialdin3376 ปีที่แล้ว

    Very helpful tutorial thank you

  • @stephenlau2845
    @stephenlau2845 ปีที่แล้ว

    Hi, Thanks for your Tutorial, How can I use API Routes database to one to one and one to many ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      You're welcome! It seems like you are asking about the database relationships when you ask about 1 to 1 and 1 to many. That is completely separate from API routes. You can connect to a database from your backend and request data - and that includes from your API routes as well as from your server components.

  • @HunterAchieng
    @HunterAchieng ปีที่แล้ว

    quick question. i keep getting the url not found error each time. Is there something I am doing wrong?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      It sounds like it. I don't know exactly what you're doing wrong but that should not be the result. You can see in the video I do not have that issue.

  • @copilotcoder
    @copilotcoder ปีที่แล้ว

    Hello sir.... whenever I try to connect to mongoDB via mongoose in app/api... it says topLevelAwait is not enabled...I cant understand why it says so

  • @MrArod1234
    @MrArod1234 ปีที่แล้ว

    Are we not using the app directory anymore? Does this come down to preference or is there a use case for using either the src or app directory?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +3

      We _are_ using the app directory. Note that it is _inside_ the src directory. When you choose to use src, it is just a container for everything else.

    • @MrArod1234
      @MrArod1234 ปีที่แล้ว

      @@DaveGrayTeachesCode Great, thank you!

  • @amansinghbhadauria2818
    @amansinghbhadauria2818 ปีที่แล้ว

    const todos : Todo[] = (await res).json();
    This code gives the below error :
    Type 'Promise' is missing the following properties from type 'Todo[]': length, pop, push, concat, and 29 more.ts(2740)
    Had to make these changes to get the todos
    const response = await res; // Wait for the Promise to resolve
    const todos: Todo[] = await response.json(); // Wait for JSON parsing to complete

  • @monyourbae
    @monyourbae ปีที่แล้ว +2

    can you make part of authentication

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      That will come _after_ this beginners series. Authentication is a more advanced topic.

    • @PlayhouseMediaGroup
      @PlayhouseMediaGroup ปีที่แล้ว

      This will be great, especially if it can also include roles, similar as the mern project we did, on teck notes app

  • @TravinskiyVladislav
    @TravinskiyVladislav ปีที่แล้ว

    Thank you, Dave

  • @adelprog
    @adelprog ปีที่แล้ว

    Thanks for sharing 👍

  • @abuhossain4274
    @abuhossain4274 ปีที่แล้ว

    sir, the way of explain is awesome ! i liked to work like the way. would you please show the front end crud part using these funs if you have time.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Remember, server components should not utilize these API routes. You can make the same requests directly in those. You could use these routes for client components.

  • @benzsfrancois1726
    @benzsfrancois1726 ปีที่แล้ว

    Amazing video! I have a question and it might be silly. If I already created a react front end using react18 and I have a MongoDB. Can I use NEXTJS as the backend rest api for that react front end ? I was watching your node/express video this month but if I could use nextjs as the backend I think it would be an awesome way to get my head around nextjs. What do you think ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      You could but I think it does have some limitations - at least currently - compared to using a traditional Node.js/Express backend.

  • @Jose_911
    @Jose_911 ปีที่แล้ว

    Awesome explained

  • @demetrycode
    @demetrycode ปีที่แล้ว

    love it

  • @zunnoorainrafi5985
    @zunnoorainrafi5985 ปีที่แล้ว

    Hi Sir,
    What icon theme are you using?

  • @orelhindi8852
    @orelhindi8852 ปีที่แล้ว

    great series man...
    one question - why do we mix up using Request type for the request and NextResponse type for the response? wouldn't it be better to stay consistent with one of them?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      It is best to only use when needed. Look at this example from the docs: beta.nextjs.org/docs/routing/route-handlers#dynamic-route-handlers

  • @elinordeniz
    @elinordeniz ปีที่แล้ว

    Hi Dave, can you plase show us how to deploy an express or next api to netlify with serverless function. This is something that I never find on TH-cam. I am sure its something many people struggle with.
    Thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      I have a video on Serverless functions with Netlify here: th-cam.com/video/J7RKx8f4Frs/w-d-xo.html
      I will show how to deploy Next.js - including the REST API - later in this series.

  • @sayidradhinpm8761
    @sayidradhinpm8761 ปีที่แล้ว

    You are much more awesome 🎉

  • @alexanderkomanov4151
    @alexanderkomanov4151 ปีที่แล้ว

    Thanks a lot!

  • @studyplanet4656
    @studyplanet4656 ปีที่แล้ว

    That was really great tutorial , if possible can you make tutorial on access and refresh token in next js .

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      I will cover auth at some time after this fundamentals series.

    • @studyplanet4656
      @studyplanet4656 ปีที่แล้ว

      @@DaveGrayTeachesCode Ok 👍👍

  • @theway_up
    @theway_up ปีที่แล้ว +1

    Hi! I have a problem, maybe you will be able to help me. I have created react app using vite. While styling it, i have noticed that the size of each element is much bigger and overall elements are bigger. I have tried to deploy project and it looks awesome. Besides, if i go to responsive mode, it is also works as it should be. Hello from Ukraine🇺🇦🇺🇦🇺🇦, Thank you for your content, it inspires me to work harder.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      This might be a good question to post in my Discord. Link in the description.

  • @saswatpranat6748
    @saswatpranat6748 ปีที่แล้ว

    I have strong skill of html,css, tailwindcss and sass can start to earn money and continue my coding journey with my side hustle while learn coding. 💰

  • @leoMC4384
    @leoMC4384 ปีที่แล้ว

    Very interesting as always. Could you make a video about migration from React to Next?? If I have a MERN project, would the migration or mutation worth it??

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Next.js is a React framework. Not much different there, but some things like routing are specific to Next.js. The backend has more differences from Node & Express, but I cover the basic set up here and middleware is the follow up to this video - coming soon.

  • @johny6767
    @johny6767 ปีที่แล้ว

    why are you not using getServerSideProps ,
    getStaticProps,
    getStaticPaths in the whole tutorial ?

  • @_rtdp_
    @_rtdp_ ปีที่แล้ว

    It's next@13.4.6 and they still haven't fixed the DELETE issue. 😭😭😭
    update: with next@13.4.6 in development mode DELETE works fine with turbo...

  • @olajireabdullahi1196
    @olajireabdullahi1196 9 หลายเดือนก่อน +1

    this is the wrong video title, It is supposed to be "How to connect with Rest API" not Build!!

  • @ICTPOPE
    @ICTPOPE ปีที่แล้ว

    Hy sir. I would like to ask this question should programmer be worrying about chatgpt AI. Replacing them ? In the future. I'm 15 and I'm new to the programming world but I'm seeing. People who don't even code. Using chatgpt AI to create. Apps and website. Without coding. . Should I focus on programming or just forget about it. Sorry for bad English 🙏

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      My answer to this frequently asked question: th-cam.com/users/shortsc8tUBvaAP1A

    • @ICTPOPE
      @ICTPOPE ปีที่แล้ว

      @@DaveGrayTeachesCodethanks ❤️🙏

  • @codernerd7076
    @codernerd7076 ปีที่แล้ว +1

    Great video like always! And the api routes would be even better if we could validate api incoming data with Zod and send back a complete array of errors!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Agreed! That would make a good follow-up outside of this series.

  • @LisSetgasy
    @LisSetgasy ปีที่แล้ว

    Dave can you do a tutorial using next api with mongoose?

  • @stalomnanotape2967
    @stalomnanotape2967 8 หลายเดือนก่อน

    A REST Api with no route protection?

  • @dopetag
    @dopetag ปีที่แล้ว

    13.4.4 still gives an error for DELETE handler:
    TypeError: Response body object should not be disturbed or locked
    at extractBody (node:internal/deps/undici/undici:6185:17)
    at new Request (node:internal/deps/undici/undici:7114:48)
    at new NextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/request.js:32:9)
    at NextRequestAdapter.fromNodeNextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:38:16)
    at NextRequestAdapter.fromBaseNextRequest (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js:20:35)
    at RouteHandlerManager.handle (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/future/route-handler-managers/route-handler-manager.js:26:57)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async doRender (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/base-server.js:936:38)
    at async cacheEntry.responseCache.get.incrementalCache.incrementalCache (/Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/base-server.js:1162:28)
    at async /Users/user/Documents/Projects/dave-gray-nextjs-13/next08/node_modules/next/dist/server/response-cache/index.js:99:36
    I had to downgrade to 13.2.4 adding some configurations to next.config.js:
    const nextConfig = {
    experimental: {
    appDir: true
    }
    }

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Yes, Next.js changes quickly. I recommend using the version of Next.js that I have in the package.json for each of these videos in this series.

  • @includerajat
    @includerajat ปีที่แล้ว

    We can get dynamic value of route same like we get for server component .
    ```
    export const GET = async (
    request: Request,
    { params: { id } }: { params: { id: string } }
    ) => {
    const res = await fetch(`${DATA_SOURCE_URL}/${id}`);
    const todo: Todo = await res.json();
    if (!todo.id) return NextResponse.json({ message: "Todo not found" });
    return NextResponse.json(todo);
    };
    ```

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Yes, you can. Go to the next video where I address this as it was mentioned in these comments before. If I don't show something in a video, that does not mean it cannot be achieved.

  • @aliraza-zt8ef
    @aliraza-zt8ef ปีที่แล้ว +1

  • @monzerfaisal3673
    @monzerfaisal3673 ปีที่แล้ว +1

    Dave. I am a straight man but i want to marry you xD

  • @etzumahkaya9583
    @etzumahkaya9583 ปีที่แล้ว

    Build api BEST bACKEND LANGUAGE JS IS MAKE TO FROONT DEV , IN Chile says pastry chef yo ypur cakes

  • @jssyntax200
    @jssyntax200 ปีที่แล้ว

    Thanks so much sir.,
    Plese make video how to manage accessToken and refreshToken from express backend from your previous lesson th-cam.com/video/CvCiNeLnZ00/w-d-xo.html using nextauth in nextjs 13

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Auth is a more advanced topic that I plan to tackle sometime after this fundamentals course is complete. 🚀