kv-store-typescript-starter-kit

A TypeScript starter kit that uses Fastly's KV Store.

Platform:
Fastly Compute
Language:
JavaScript
Repo:
https://github.com/fastly/compute-starter-kit-typescript-kv-store

Use this starter

Using the Fastly CLI, create a new project using this starter somewhere on your computer:

$ fastly compute init --from=https://github.com/fastly/compute-starter-kit-typescript-kv-store

Or click the button below to create a GitHub repository, provision a Fastly service, and set up continuous deployment:

Deploy to Fastly

Understanding the code

./src/index.ts

This is the entry point of the application, an event-listener is attached to the fetch event, which calls the application code and include some generic exception handling, which would print any uncaught exception to the stderr and return a response with a HTTP 500 status to the user-agent.

./src/app.ts

This is where the majority of our application code lives. A single async function is exported named app, which is the function that recieves the incoming FetchEvent and returns a Response instance, which will be sent to the user-agent.

Running the application

To create an application using this starter kit, create a new directory for your application and switch to it, and then type the following command:

npm create @fastly/compute@latest -- --language=typescript --starter-kit=kv-store

To build and run your new application in the local development environment, type the following command:

npm run start

Deploying the project to Fastly

Note that Fastly Services have to have unique names within a Fastly Account.

To create and deploy to a new Fastly Service run the command and follow the instructions:

npm run deploy

That is it, we now have a Fastly Service, a Fastly KV Store and have them linked together!

You can view real-time logs for the Fastly Service by running:

npx fastly log-tail

Adding entries to the KV Store

It is possible to add key-value pairs to an KV Store using the Fastly CLI like so:

npx fastly kv-store-entry create --store-id=$FASTLY_KV_STORE_ID --key-name=$KEY --value=$VALUE

For example, here is how you could add to the KV Store named my-store a key named readme whose value is the contents of README.md:

npx fastly kv-store-entry create --store-id="$(npx fastly kv-store list --json | jq -r '.Data[]|select(.Name=="my-store").ID')" --key-name="readme" --value="$(cat README.md)"

Next steps

Starters are a good way to bootstrap a project. For more specific use cases, and answers to common problems, try our library of code examples.