Next.js 13 API Routes (NEW)

Sdílet
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

Komentáře • 59

  • @daaatboy
    @daaatboy Před rokem +4

    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.

  • @sdsim1
    @sdsim1 Před rokem +1

    Fantastic! I always get some valuable knowledge from everyone of your videos 👍😁

  • @randolphmaysondy7983
    @randolphmaysondy7983 Před rokem

    Thank you Tuomo! Helped me a lot :)

  • @futuristic-
    @futuristic- Před rokem +2

    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?

    • @blazi_0
      @blazi_0 Před rokem

      Yeah , u simply fetch basepath/blogposts

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem

      Yeah you can use fetch to call them!

    • @NezNez
      @NezNez Před rokem

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

  • @maskman4821
    @maskman4821 Před rokem

    This is an awesome Next 13.2 api route tutorial, simple and clear explanation, easy to follow, please dive deeper, thank you 🤩

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem

      Glad you liked it! The deep dive is now published on the channel!

  • @xiiEJRAM
    @xiiEJRAM Před rokem

    I love to watch your tutorials , keep going

  • @dzakirz
    @dzakirz Před rokem +1

    can you please make a video for implementing next-auth in app/api which was previously in pages/api, thanks

  • @mas2ai
    @mas2ai Před rokem

    Thanks for the video explaining API Routes. Please make more video in detail about these API Routes and what else is possible with them.

  • @anton9410
    @anton9410 Před rokem

    Thanks for the updated info!

  • @heyjitendra
    @heyjitendra Před rokem

    great video mate, would love to see more of these.

  • @mertvural8579
    @mertvural8579 Před 11 měsíci

    when will we use this? import { NextResponse } from 'next/server'

  • @melissabanoengarde
    @melissabanoengarde Před rokem

    Clutch, always timely 🔥

  • @ronaldpaek
    @ronaldpaek Před rokem

    Will route handlers work with next auth?

  • @shafinulislam562
    @shafinulislam562 Před rokem +1

    Hey, great video. Any idea how we can implement NextAuth with route handlers now?

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem +2

      Havent tried that yet but planning on testing it out!

  • @bpmbyjulian
    @bpmbyjulian Před rokem

    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.

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem +2

      I just published a video where I show how to get the body in POST request!

  •  Před rokem

    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!

  • @musicaddict-bs6el
    @musicaddict-bs6el Před rokem

    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)

    • @chrismixlist
      @chrismixlist Před rokem

      I am wondering about the same thing

    • @matiastika1329
      @matiastika1329 Před rokem

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

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem

      I just published a video where I show how to get the body in POST request!

  • @skverskk
    @skverskk Před rokem

    Well done. And, easy to follow

  • @theBarracuda_
    @theBarracuda_ Před rokem

    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; }'.

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem +1

      Cheers! Not sure about the error, maybe something to do with the object you are calling the .json() with

  • @devyb-cc
    @devyb-cc Před rokem

    already implemented in my website. the metadata api is very helpful 👍

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem +1

      Yeah it seems very useful!

    • @devyb-cc
      @devyb-cc Před rokem

      @@TuomoKankaanpaa can't wait to see, what next features to be implemented.

  • @madrugamac
    @madrugamac Před rokem

    how get req.body on post method ?

  • @Mike-ck2ls
    @Mike-ck2ls Před rokem

    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.

    • @Mike-ck2ls
      @Mike-ck2ls Před rokem +1

      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 });
      }

    • @TuomoKankaanpaa
      @TuomoKankaanpaa  Před rokem

      Yes exactly! I just also published a video teaching this and bunch of other stuff you can do with route handlers.

  • @devdariill
    @devdariill Před rokem

    pls, how use Response to do a res.revalidate('/')

  • @wassu8499
    @wassu8499 Před rokem

    I am waiting for next video sir ?

  • @Happyday-nn6rh
    @Happyday-nn6rh Před rokem

    first always is best

  • @hartono9583
    @hartono9583 Před rokem

    loveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

  • @blazi_0
    @blazi_0 Před rokem

    This is so powerful

  • @alsherifkhalaf7385
    @alsherifkhalaf7385 Před rokem

    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 ?