SvelteKit API Routes & Endpoints

แชร์
ฝัง
  • เผยแพร่เมื่อ 6 ส.ค. 2024
  • If you find my content useful and want to support the channel, consider contributing a coffee ☕: hbyt.us/coffee
    SvelteKit is a framework for building modern, high-performance, browser-based applications. It was developed by the team behind the popular Svelte framework and is powered by Svelte. Unlike other JavaScript frameworks, it doesn't use a virtual DOM or deliver a bloated and slow application.
    In this SvelteKit tutorial, I demonstrate how to use endpoints within SvelteKit, which enables you to create a REST API that can be consumed by your application or external clients.
    📂 Final Code
    github.com/huntabyte/svelteki...
    💽 Loading Data in SvelteKit
    • Loading Data in Svelte...
    ⏪ Previous Video (Form Actions in SvelteKit)
    • Form Actions Made Simple
    📚 Resources Mentioned In This Video
    - SvelteKit Docs: kit.svelte.dev
    - DummyJSON API: dummyjson.com
    🚀 Become a channel member: hbyt.us/join
    💬 Discord: hbyt.us/discord
    🐦 Twitter: hbyt.us/twitter
    🖥️ Setup Stuff: hbyt.us/gear
    🔖 Chapters:
    00:00 - Introduction
    00:12 - What is a +server.js
    00:40 - GET function
    02:26 - Request Headers
    04:50 - Using Environment Variables
    05:45 - Fetching External Data
    06:25 - Query Params
    08:28 - POST function
    10:20 - Integrating with +page.svelte
    13:48 - Route Params
    17:46 - Conclusion
    📃 Topics Covered:
    - API routes in SvelteKit
    - What does a +server.js do?
    - How to create API routes in SvelteKit
    - How to create endpoints in SvelteKit
    - How endpoints work in SvelteKit
    - How API routes work in SvelteKit
    - SvelteKit crash course
    - What is SvelteKit?
    __________________________________________
    (Affiliate links may be included in this description. If you choose to purchase a product from one of those links, I may receive a small commission at no cost to you. Thank you for supporting the channel!)

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

  • @philippecasasnovas6603
    @philippecasasnovas6603 ปีที่แล้ว +60

    Hello
    I love your videos.
    I have three difficulties:
    1- I don't speak English very well (Thanks Google translate)
    2- I am new to full stack programming for my pleasure
    3- I am 63 years old ;-)
    I watch each video at least 10 times in slow motion with French subtitles and I'm very happy to be able to do what I want.
    Thank you once again your videos are of excellent quality.
    greetings from france

    • @Huntabyte
      @Huntabyte  ปีที่แล้ว +5

      Thank you so much for the kind words! Google translate did a phenomenal job here, and I am thrilled that you find my videos useful!

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

      Beaucoup de courage Papy

  • @codenx2
    @codenx2 ปีที่แล้ว +40

    Love it. I have been doing sveltekit for 3 years, never experience such detailed and precise content in the community.

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

      Thank you, there is definitely more content to come. Once I have videos of the basics covered, I intend on doing some more in-depth projects! Please let me know if there’s anything specific you’d like to see!

    • @codenx2
      @codenx2 ปีที่แล้ว +10

      ​@@Huntabyte In my experience
      1. Everyone faces CORS issue, that will be helpful
      2. In almost all projects we need authentication
      3. Load data once at server and preserve the data all over the app while making client side routing without making a new api request on each navigation.

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

      @@codenx2 would love to see simple postgresql crud using pg and sveltekit

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

      @@DionisiusWahyuAdiSaputra are there some example about crud using postgress and sveltekit. thanks in advance.

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

      This is a really good tutorial, you're right! As a person who was using Svelte three years ago, before the SvelteKit days, I'm "pretty stoked 'bro'," as it is said, by some. 😆Digging this tutorial, it covers the bits most toots skip over.

  • @tombarfoot9693
    @tombarfoot9693 ปีที่แล้ว +10

    I really like your approach to teaching, the shorter the preamble the better. The content here on svelte is fantastic, I've learned a lot.
    I also would like to see real world examples on difficult use-cases such as authentication, using hooks.js, proper error handling, protected routes etc.
    Really like the channel, thanks!

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

      Thank you for the kind words! There is definitely such content in the works!

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

    Your video explanation together with the new Sveltekit data loading features (server load, server endpoints and stuffs),, makes lots of things clearer.

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

      Glad to hear that, thank you!

  • @Mexad0n
    @Mexad0n ปีที่แล้ว +6

    really like your references to SvelteKit API _(in all videos)_ with more useful examples and explanation than in official docs that are not for me as clear as your examples of use. Thanks a lot

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

      Thank you, I'm glad to hear that!

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

      I second that about how you reference the API, I really like that so you see where to 'go' in the future! Great!

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

    Dude, you have become my goto for anything svelte/sveltekit related. Nice work!

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

      I'm glad to hear that!

  • @Allformyequine
    @Allformyequine ปีที่แล้ว +5

    These are great videos, I'm so glad you are doing these on SvelteKit! Thank you for your effort!

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

      My pleasure!

  • @haraldndb.1250
    @haraldndb.1250 ปีที่แล้ว +1

    Great! Discovered your channel yesterday and i am excited.

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

    I realize you said you probably wouldn't set it up this way IRL, but the benefit of doing so is that if you change your backend, ie: to another database, you can just change your API routes to the new database calls and the UI pages won't need to be changed (or at least not as much, depending on what has changed in the APIs).

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

    Superb video, thank you!!
    And this is the LAST STEP Guys,
    to redirect to the [postId] page when clicking on the post in the "posts" page
    (and I also added some styling to the "cards" of the posts):
    /posts/+page.svelte:
    import { goto } from '$app/navigation'
    export let data
    const { posts } = data
    const handleClick = (postId) => {
    goto(`/posts/${postId}`)
    }
    {#each posts as post}
    handleClick(post.id)}>
    {post.title}
    {post.body}

    {/each}
    .card {
    background: rgba(40, 104, 224, 0.753);
    color: #000;
    width: 90%;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    margin: 1rem 1rem;
    font-size: 0.75rem;
    padding: 0.75rem 0.75rem;
    cursor: pointer;
    }

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

    Perfect intro to routing API, thank you very much

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

    Great video - incredibly helpful! All of your sveltekit content is very much appreciated.

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

    I always loved Svelte, but man, you are making me rethink on the whole React world, i used React for many years and i use it at work too now with Next 13, but i always loved the simplicity of Svelte. Now with SvelteKit is at another level, so simple! thanks for the videos, save me a lot of time on the Doc. :D Still debate tho if i like this + thing in front of the file names.

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

      You're very welcome! You get used to the '+' in front of the routes after a week or two and it becomes second nature!

  • @SRG-Learn-Code
    @SRG-Learn-Code ปีที่แล้ว +4

    Really good, seems like authentication&authorization is a good next topics. I'm interested in hooks since there are also clients hooks now? I'd love to watch your approach into it. I know auth it's a beast on it's own, maybe authenticationmay be external (I would like to know more about firebase authentication) to explain sveltekit authorization.

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

    Have learned a lot from your tutorial, thank you so much 🙏

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

      Happy to hear that!

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

    Splendid examples... 😃😃 It showed how your own APIs can power the front end. The example can be easily extended to include a database or cloud service to store the data. I should say a Razor sharp Content.

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

      Thank you so much! I appreciate the kind words!

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

    Hi et thanks for that series about SvelteKit. Great content !

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

      Thank you, I'm glad you've enjoyed it. There are still more videos to come!

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

    Best learn content for SvelteKit so far! Like it very much.
    I really would like to see how to get a JSON object into the endpoint action function. As far as I understood the endpoint action function only gets FormData which is not an JSON object and difficult to handle (and save to MongoDB) if the form is hierachical (e.g. an aray of data entries inside the JSON object).

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

      You can access the request body, however, if you'd like to use FormData, you'd need to parse the data from the form and build a JSON object out if it.

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

      @@Huntabyte Thank you for your quick respond. request.json() inside the action function throws a 500 error. request.formData() is working, but I would rather get JSON data.

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

    Great video - please keep them coming!!!

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

      Thanks, will do!

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

    Amazing explanation! Thank you very much! :)

  • @petercli
    @petercli 11 หลายเดือนก่อน

    Great way for hands-on learning.

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

    This helped tremendously, thanks!

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

      You're very welcome!

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

    Excellent again! Thank you.

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

      Thanks for the kind words, Michael! I am glad this video was useful to you!

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

    Pretty good video, definitely useful, my only complaint might be (more on the petty side possibly) but when doing a video on get or post, a little confusing to have the thing you are getting are a post. Otherwise an excellent video.

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

      At the time, using `GET` from a form to an endpoint didn't work in SvelteKit, but they do now!

  • @grigorfanyan1821
    @grigorfanyan1821 5 หลายเดือนก่อน

    thanks man, very helpful

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

    Thank you again for another useful video showcasing this functionality. One video I'd like to see is authorization checking for basic user navigation. Like a hooks video showing how to implement an auth checker every time a user changes page and how that can relate to SSR vs CSR. I've been struggling to figure that out for a project.
    I've already been trying to make use of hooks, but seems the docs lack in explaining (or I'm just not understanding).
    To elaborate on this, I was testing making a GET request to my API and this was triggered inside of +layout.js within the exported load function. This works for the SSR initial rendering, but the need is to have it triggered upon client side routing. I don't know what the function to export is called to trigger this code on every client side "page change". I thought by having it within layout, it would still be acknowledged when navigating using CSR.
    Maybe I'm trying to solve this the wrong way, idk haha
    Also, thanks for the recommendation of Thunder Client. Nice to have it implemented within VS code

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

      I definitely have some content around authentication/authorization in the pipeline! Thank you!

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

      Looking forward to it. 👍🏼 Great stuff so far.

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

      Following up on this, I've found something that helps better understand the hooks.server.js setup. Note, this code should not be used in production, but I think it helps show a basic example of checking some variables and redirecting based on their condition.
      To briefly explain...
      1. It's setting some variables to determine the truthiness of the route being requested via regexp tests. (if it's the login page or an API route request behind the scenes. i.e. api request)
      2. Retrieving the user login token from the cookies
      3. If the token is not set and the page / route requested is not the login page or an API route, redirect to the login page (to login and thus, set the login token needed). The API logic is needed, otherwise, any request to API will be "redirected" so to speak.
      4. If token is set and currently visited page is login page, redirect to home page. This assumes the user is logged in. Note, this is unsafe and needs proper validation before redirecting
      5. If neither of the two conditions above match when visiting a route / making a request, it will allow the request.
      export async function handle({ event, resolve }) {
      const isLogin = /^\/login/.test(event.url.pathname)
      const isApi = /^\/api/.test(event.url.pathname)
      const token = event.cookies.get("token")
      // If token is not set and route requested is not ~"/login" or ~"/api",
      // redirect the user to the login page.
      if (!token && !isLogin && !isApi) {
      return Response.redirect(`${event.url.origin}/login?method=badge`)
      }
      // Else if token is set and user is on login page,
      // redirect to the home page because they would be logged in.
      // Will do more validation to secure this.
      else if (token && isLogin) {
      return Response.redirect(`${event.url.origin}/`)
      }
      // Otherwise, let any route proceed
      else {
      return await resolve(event)
      }
      }
      Again, this should not be used in production without further cleanup and proper token storage and validation etc. It just helps someone new conceptualize the logic. Credit to this SO post...
      stackoverflow.com/questions/72300836/sveltekit-hook-prevents-endpoint-request

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

    Great work !

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

    Please post a video on "How to use/connect MongoDB or other databases with SvelteKit".
    Lets Go Sveltekit Fullstack ✊✊

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

      I have a video on Full-Stack with Prisma on my channel!

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

    You are good at this. I would like to request a video showing us how to publish a component to npm.

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

      Great suggestion, I will certainly take that into consideration!

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

    so if i am using supabase as backend is it good practice to use sveltekit api as middleman to call supabase or just call supbase directly as I am currently. How does it know auth user if I pass through sveltekit api. And not sure how to implement limits on users and stuff like that yet but would be interesting to see. Amazing video opens new world of ideas using api outside of application

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

    awesome! Love it! 👍

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

      Thank you! Cheers!

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

    I watched this video and your other (awesome) one explaining the loading data in SvelteKit. I don't understand how you figure out if you need to use get or load :/ So for pulling in basic blog posts from a CMS is it better to use the load function? I do understand to use the +page.server.js so I can hide my private key, just not understanding which function to use for my use case of pulling in blog posts ... and how do you decide which to use :/ I guess after re-watching that you recommended to use the Load function for what I'm trying to do. WOW, I think I might be slowly getting it! THANK YOU for all of these awesome videos! I learned a ton form them :)

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

      I'm glad I could help! The Discord server is always willing to lend a hand, feel free to join anytime!

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

      @@Huntabyte Awesome I will join for sure!! Thank you!

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

    good video thank you so much❤

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

      You're welcome, thanks for taking the time to comment!

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

    Great video Again! , if am correct, my take away, it's better to have server endpoints if data is going to be accessed in different clients/components?

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

      Different clients, 100%! As far as components/pages it would depend on how you’d like to structure your app, but rather than defining all the logic of fetching and transforming the data in each page.server, you could place it all inside of the endpoint and then just fetch from that endpoint in each of those load functions!

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

      @@Huntabyte perfect. Thanks for the response! Can't wait for the Auth video!

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

    Great video

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

    How do you go about deciding whether to use functions inside of Form Actions, ie. inside a +page.server.ts file, VS using fetches from a SvelteKit API endpoint (that contains the functions)?
    In my scenario my priority is to ensure certain functions are server-only, but wondering which way to go: FActions or SKEndpoints..

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

      If it’s going to be consumed by anything other than a form being submitted on a page I will use an endpoint, otherwise a form action!

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

      @@Huntabyte do you have a tute on that in ts by chance?

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

    My sveltekit API route needs to fetch data from external services which takes time. So deploying on vercel or netlify gives error 'Timeout'. So they has a limit how long a connection can be open. How to resolve this issue? Suggest any platform to host sveltekit app for free tier.

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

    Amazing videos, i just hope you could do typescript instead

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

      That’s a possibility. All of my recent livestreams are typescript, but I will consider for videos as well!

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

      Trying to make an endpoint with TS atm and I am slowly but surely losing my mind haha

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

      @@thekinoreview1515 My recent and videos moving forward utilize Typescript. At first I was trying to not add too much that might confuse someone not familiar with it, but realized it's too powerful not to use.

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

      @@Huntabyte Thank you!

  • @it-s-me-mohit
    @it-s-me-mohit ปีที่แล้ว +1

    Great video. But what I don't understand is why would we want to create our endpoints if we are already doing it in the BE API for example.

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

      Great question! Endpoints COULD be your backend API. In the video where I fetched data from the dummyjson API, you could replace those calls with calls to your database using Prisma or another ORM. I just didn’t want to add the complexity of a database to a video focused on the endpoints themselves.
      It would definitely be redundant to have a separate backend API and endpoints unless there was a very specific need for it, so you are correct.

    • @it-s-me-mohit
      @it-s-me-mohit ปีที่แล้ว

      @@Huntabyte thanks makes sense

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

    For people getting a "Connection was refused by the server." error when querying thunder, try querying "[::1]:5173/api/posts" instead of "localhost:5173/api/posts".

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

      you came in time.. do you have any problems loading the data in +page.js?

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

      @@arianitonline8748 Nope, everything besides what I mentioned worked well.

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

      Could you explain why this works? Or if there is a way to fix the original method?

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

      Yes, that works for me . I never saw this notation before-is it 3 digits x.x.x like with IPV4 ?

    • @caleb6963
      @caleb6963 2 หลายเดือนก่อน

      Thank you, very helpful!

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

    Can you do some TS examples? Like a generic fetch which returns some typed objects.

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

    does it mean if i have 10 different api endpoints with multiple post and get requests i have to create different folder for each? 😮‍💨

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

    I know it’s not the point, but would have been better to see usable code here. Like moving the auth check to a layout so not duplicating code, handling errors instead of removing auth check, using built in functions like redirect and error, etc.
    For other video ideas,
    Would be cool to see grouped layouts, why when and how to use them
    And error handling in general, when to show an error page, how to construct them to be appropriate for the end user, and when or how not to use them

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

      Thank you for the feedback! I went back and forth with how to structure this video and what direction to take it in and ultimately decided to leave it at just showing some of what is possible with endpoints and how they work at a surface level.
      I do intend to create more videos in the future that include more complete examples/walkthroughs with regards to authentication, error handling, etc.
      It’s sometimes difficult to find the right balance of making it easy for a complete beginner to wrap their head around while also making it realistic and practical. I hope to improve that balance with every video which feedback like this enables me to do, so I appreciate it!

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

      @@Huntabyte For me it's pretty much completely impossible to grasp or understand until I see it being actually used. So much time I spend in tutorials going, okay but why would I actually do that. Not necessarily this video, but +1 for practical stuff from me :)

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

    There is any way to keep all the API requests in just on file?

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

      Unfortunately, since SvelteKit uses directory-based routing, I don't believe this is possible without some potentially undesirable workarounds. If you intend on creating a more feature-rich API, I would suggest looking at something like NestJS

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

      @@Huntabyte That is ok, it makes sence, on question how do you handle the update in the form? since I think we are not able to use the form with the PUT method

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

    +page.js, +page.server.js, +server.js are confusing, +page.server.js seems does the thing +server.js do except +server.js serves as a standalone api, what about +page.js ? it seems runs before page mounted and does client side prerender, is this true ? I am confused 😅

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

      The best way I like to think of these is like this: +server.js can be used like an API route and be consumed by multiple different pages within your application, or a separate application altogether (think of a mobile app for your site). +page.server.js takes care of loading data from the server (if you need to use private environment variables to load your data, you will do this here) and is also where you define form actions. +page.js is ran on both the server and the client, so you can't access private environment variables, and would be useful for accessing data from a public API that doesn't require an API key.

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

    Interestingly, I can't get thunder client to work, but postman does 🤔

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

    does this still work?

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

    Need error handling on this! How do you catch errors?

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

      I made a video on error handling

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

    I can't upvote, it's at 420

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

    Keep going!