|Author||Jef Meijvis||Publish date||13/12/2022|
|Title||Sveltekit API endpoints||Id||6|
|Source||006-sveltekit-api-endpoints.md||Render timestamp||Dec 06, 2023, 06:08:30 AM (GMT+1)|
|Title||Sveltekit API endpoints|
|Render timestamp||Dec 06, 2023, 06:08:30 AM (GMT+1)|
Share this post:
Sveltekit routing allows for precise control of the response by creating a “+server.js” file (or .ts). We can export a function for each of the HTTP verbs such as GET, POST, PUT, PATCH, etc.. This way, we’re able to create an API. All our code will run server-side, allowing us to access environment variables, the file system, a database, …
Image: Svelte logo
Can you create an entire enterprise-grade standalone API using Sveltekit endpoints? Yes! Should you? Probably not. While it’s entirely possible, I feel like a few endpoints bundled together with your front-end code make more sense.
First we will export a function called GET. Each of the HTTP verbs is a possible function name that we can export at the endpoint file.
The function will take a RequestEvent as input parameter. The type definition can be found at “./$types”. A RequestEvent allows for querying the search parameters, such that a GET call to /api?firstName=Jef&lastName=Meijvis will return “Hello Jef Meijvis” as a response.
When we omit the search parameters, we will get the default response “Hello Default firstname Default lastname”.
We can easily create a POST endpoint in the same file, like so:
The only difference with our GET request is that instead of getting request info from the search parameters, we get it from the body this time. To get the same response as with the GET request, we can send a POST request to /api with the following body:
When returning a response from your endpoint, you might want to return customized headers. We can do this by supplying the Response constructor shown above with an additional ResponseInit object. This object has a 'headers' property that we can supply with the required headers in key-value format. For example, when we want to cache the API response for 1 hour (3600 seconds) we can do this by adding the following headers:
When we call these endpoints from a clientside web application, we will need to serve a response to the OPTIONS preflight request. We can accomplish this by creating a Sveltekit hook at src/hooks.server.ts
The code intercepts any request with the OPTIONS verb, and returns a 200 OK response. Any other requests are just handled as before.
When we host our Sveltekit project on a cloud provider such as Vercel, all our endpoints will become publicly available. To prevent CORS issues, we need to do one final thing. When hosting a Sveltekit project with endpoints on Vercel, we need to create a vercel.json file at the project root with the following configuration:
Different adaptors and hosting providers will probably require a different setup or configuration to allow for CORS.