Skip to content

JavaScript SDK

The Val Town TypeScript SDK lets you interact with our REST API from the comfort of a typed client that works well with editor autocomplete.

The Val Town SDK runs in:

  • Val Town
  • Node.js 18 LTS+
  • Deno v1.28.0+
  • Bun 1.0+
  • Cloudflare Workers
  • Vercel Edge Runtime

Getting started in Val Town

The quickest way to get started with the SDK is to use it in Val Town, for example by forking this val.

Using the SDK in Val TownRun in Val Town ↗
import ValTown from "npm:@valtown/sdk";
const vt = new ValTown();
// print your username
const me = await vt.me.profile.retrieve();
console.log(me.email);
// list some of your vals
const { data: vals } = await vt.users.vals.list(me.id, {});
console.log(vals);
// list vals you've liked
const { data: likes } = await vt.me.likes.list({});
console.log(likes);

Authentication is set by the VAL_TOWN_API_KEY environment variable, which is automatically set within Val Town. You can control the API scopes of that key in your val’s settings page.

Getting started in Node.js

Here is how to get started with the SDK, with Node.js, writing ESM. You should have Node.js already installed, version 18 or newer. There are many ways to set up JavaScript and TypeScript projects, and it’s likely that you already have a project you intend to integrate against, so we don’t document every approach.

Setting up an example Node.js project
# Create a directory for your project
mkdir example-project
cd example-project
# Create a package.json file
npm init
# Install the SDK
npm install @valtown/sdk

Create a file named index.mjs. Note that it needs to end with .mjs, not .js, because this file is using ESM import syntax. Alternatively, you can add "type": "module" to your package.json file.

index.mjs
import ValTown from "@valtown/sdk";
const valTown = new ValTown();
async function main() {
const myProfile = await valTown.me.profile.retrieve();
console.log(myProfile);
}
main();

Finally, the API expects to be authenticated with an API token, so create an API token on Val Town, and set it in your terminal environment:

Setting your Val Town API Token
export VAL_TOWN_API_KEY=your api token

Now you should be able to run index.mjs and get your profile information:

Running index.mjs and getting profile information
node index.mjs
{
id: '19892fed-baf3-41fb-a5cc-96c80e95edec',
bio: '👷 Building Val Town',
username: 'tmcw',
profileImageUrl: 'https://img.clerk.com/eyJ0eXBl…',
tier: 'pro',
email: 'tom@macwright.com'
}