Skip to content
EndpointsView the code for this module.

At this point in the course we've gone over routing to pages, but we can also route to endpoints. Endpoints are server-side routes, so They provide "backend" functionality within the SvelteKit application providing a great place to, for example, make an external API request.

Endpoints are modules written in .js or .ts files that export functions corresponding to HTTP methods. These endpoint files become API routes in our application. For example, our [name].svelte page might request data from /product/sticker, which could be represented by the endpoint src/routes/product/sticker.js .

Go ahead and create this file within our product folder called /product/sticker.js. This will trigger the creation of an endpoint which is basically a server-side route for our app. Since this is technically a route, we keep our endpoints in our routes folder. The first thing you probably notice is the interesting file name we gave our endpoint. Firstly, rather than ending in .svelte like our previous page files, our endpoint ends in .js. This is because, as already mentioned, endpoints are written in .js or .ts files. Now, if we wanted, we could also add a file extension before the .js like this, /product/sticker.json.js, which just tells us the type of data that will be returned from the endpoint. All together, our file name is saying that we have an endpoint at /producst/sticker , because it follows the same routing structure as our site, that is written in a .js file and will return json data. This is optional, so I'm going to chose not to add it for this example, and you'll see why in a bit.

As mentioned earlier, endpoints export request handler functions corresponding to HTTP methods. Request handlers make it possible to read and write data that is only available on the server. For example, within this file we can export a GET, POST, PATCH, DELETE ... or any valid HTTP method. Endpoints also have access to fetch in case you need to request data from external APIs. For example, within our endpoint file, we can make a GET request on this route by exporting an async function called get like this.

export async function GET() {}

Now, we can reach out to a database and retrieve some data. Since we do not have a database set up, let's instead return an object with some hard coded data representing the response. In our example, let's declare our value product, and return the product in our body like this.

export async function GET({ params }) {
  const product = {
        name: 'sticker'
        src: 'https://cdn.shopify.com/s/files/1/0434/0285/4564/products/Cup-front-black.png?v=1623159405'
        price: '$10'
    };
  return {
    body: { product }
  };
}

Now, this is the basics of what might be returned by an endpoint. Remember, this is server side, so it will not be available to the client where you typically don't want to use any sensitive information for security reasons. As previously mentioned, endpoints are serverless routes. Endpoints follow the same routing structure as our site, so Just like with our page components, our endpoint routes are determined based on the name of the file. If we route to /product/sticker.js, we can visit this endpoint page just like we would a normal route, and we can view the json data being returned by this endpoint. Again, this is generated server-side, so we can reach out directly to a database and use sensitive information here.

Currently our endpoint is only returning our sticker data, but we want it to use a dynamic parameter, just like our product page does, to dynamically fetch data associated with whatever product page we are currently on. We are able to use dynamic parameters with endpoints the same way we use them with pages. Let's update our endpoint name to /product/[name].js, where name is the dynamic parameter, so it will once again be within square brackets. Our method accepts an object of parameters, so in this case we can access our dynamic name by passing in params, and using it like this.

export async function GET({ params }) {
  const name = params.name;
}

Now we could use this to reach out to a database and fetch data associated with this specific product. We don't have a database set up, but for the sake of example that might look something like this.

import db from database;

export async function GET({ params }) {
    var product = db.collection.find(params.name)
    return {
        body: {
            { product }
        }
    }
}

I'm going add a hard coded array of products, and use our dynamic param to search this array and return the correct product to sort of mock a database.

const products = [
  {
    name: 'cup',
    price: '$10',
    quantity: 1,
    src: 'https://cdn.shopify.com/s/files/1/0434/0285/4564/products/Cup-front-black.png?v=1623159405',
  },
  {
    name: 'shirt',
    price: '$10',
    quantity: 1,
    src: 'https://cdn.shopify.com/s/files/1/0434/0285/4564/products/short-sleeve-t-shirt-0.png?v=1622902418',
  },
  {
    name: 'jacket',
    src: 'https://cdn.shopify.com/s/files/1/0434/0285/4564/products/bomber-jacket-0.png?v=1622902777',
    price: '$80.00',
    quantity: 1,
  },
  {
    name: 'sticker',
    src: 'https://cdn.shopify.com/s/files/1/0434/0285/4564/products/Sticker-mock.png?v=1623256356',
    price: '$8.00',
    quantity: 1,
  },
];
export async function GET({ params }) {
  let product = products.find((product) => product.name === params.name);

  return {
    body: { product },
  };
}

Now that we've created our endpoint, let's use this endpoint in our page to display the data returned from the endpoint. Notice the name of our endpoint is the same as the page that we are fetching its data in. Anytime an endpoint's filename is the same as a page (except for the extension), the page gets its props from the endpoint. We call these page endpoints, and they allow you to pass in props directly from the endpoint. If you remember earlier in this module when we created out endpoint, I decided not to add the .json file name extension. This is because page endpoints cannot use this. We will learn how to use this with standalone endpoint in the next module.

Looking back at our endpoint, we are returning our body which contains a single value, product. This body is what allows us to have props passed directly into the page. Back in our /products/[name].svelte page, we can write export let product within our <script> tag. Now our product data is coming directly from our endpoint, so the info being displayed on the page will change with the dynamic param, name.

As you can see, page endpoints allow you to run code server side in svelte by exporting an async get function. Now, what if we want to hit this same endpoint from a different page that has a different name than the endpoint? Well, to do that we will need to use the load function which we will go over in the next module.