Back to Templates

Svelte Route Protection

API key authentication in Svelte

Written by
harshsbhat
Framework
Svelte
Language
Typescript
API key authentication in Svelte

Svelte Route Protection with Unkey

This project demonstrates how you can protect your Svelte API Routes with Unkey

Prerequisites

Unkey account

Setup Unkey

  1. Create an unkey account
  2. Create a new API. Copy the API ID.
  3. Go to permissions and create a new permission named access-unkeyed-route
  4. Now go to roles and create a new role and select the withAuth permission for the role.
  5. Go to apis again and create a new key
  6. Click on the "Keys" tab.
  7. Select the key you created.
  8. Click on the "Permissions" tab.
  9. Check the role's checkbox to assign the role and permission to the key.
  10. Create a new root key from the settings/root-key with permission to create and read keys.
  11. You can follow this link to create the root key on the workspace level. https://app.unkey.com/settings/root-keys/new?permissions=api..create_key,api..read_key
  12. Alternatively, follow this link to create the root key on the API level. Replace the API id with your API id. https://app.unkey.com/settings/root-keys/new?permissions=api.api_id.create_key,api.api_id.read_key

Setup Environment Variables

cp env.example .env and add the following variables:

1UNKEY_API_ID=""
2UNKEY_ROOT_KEY=""

Quickstart

Install all the dependencies

1pnpm install

Run the app. It should start at port 5173

1pnpm dev

Usage

Create a key using the following api/createKey route

1curl http://localhost:5173/api/createKey

Now access the protected route which verifies the key

1curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:5173/api/protected

Protect your API.
Start today.

2500 verifications and 100K successful rate‑limited requests per month. No CC required.