Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
275 changes: 275 additions & 0 deletions docs/docs/00100-intro/00200-quickstarts/00275-deno.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
---
title: Deno Quickstart
sidebar_label: Deno
slug: /quickstarts/deno
hide_table_of_contents: true
---

import { InstallCardLink } from "@site/src/components/InstallCardLink";
import { StepByStep, Step, StepText, StepCode } from "@site/src/components/Steps";

Get a SpacetimeDB Deno app running in under 5 minutes.

## Prerequisites

- [Deno](https://deno.land/) installed
- [SpacetimeDB CLI](https://spacetimedb.com/install) installed

<InstallCardLink />

---

<StepByStep>
<Step title="Create your project">
<StepText>
Run the `spacetime dev` command to create a new project with a SpacetimeDB module and Deno client.

This will start the local SpacetimeDB server, publish your module, and generate TypeScript bindings.
</StepText>
<StepCode>

```bash
spacetime dev --template deno-ts
```

</StepCode>

</Step>

<Step title="Explore the project structure">
<StepText>
Your project contains both server and client code.

Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `src/main.ts` to build your Deno client.
</StepText>
<StepCode>

```
my-spacetime-app/
├── spacetimedb/ # Your SpacetimeDB module
│ └── src/
│ └── index.ts # Server-side logic
├── src/
│ ├── main.ts # Deno client script
│ └── module_bindings/ # Auto-generated types
└── deno.json # Deno config and tasks
```

</StepCode>

</Step>

<Step title="Understand tables and reducers">
<StepText>
Open `spacetimedb/src/index.ts` to see the module code. The template includes a `person` table and two reducers: `add` to insert a person, and `say_hello` to greet everyone.

Tables store your data. Reducers are functions that modify data — they're the only way to write to the database.
</StepText>
<StepCode>

```typescript
import { schema, table, t } from 'spacetimedb/server';

export const spacetimedb = schema(
table(
{ name: 'person', public: true },
{
name: t.string(),
}
)
);

spacetimedb.reducer('add', { name: t.string() }, (ctx, { name }) => {
ctx.db.person.insert({ name });
});

spacetimedb.reducer('say_hello', ctx => {
for (const person of ctx.db.person.iter()) {
console.info(`Hello, ${person.name}!`);
}
console.info('Hello, World!');
});
```

</StepCode>

</Step>

<Step title="Run the client">
<StepText>
In a new terminal, run the Deno client. It will connect to SpacetimeDB and start an interactive CLI where you can add people and query the database.
</StepText>
<StepCode>
```bash
# Run with auto-reload during development
deno task dev

# Or run once

deno task start

```
</StepCode>
</Step>

<Step title="Use the interactive CLI">
<StepText>
The client provides a command-line interface to interact with your SpacetimeDB module. Type a name to add a person, or use the built-in commands.
</StepText>
<StepCode>
```

Connecting to SpacetimeDB...
URI: ws://localhost:3000
Module: deno-ts

Connected to SpacetimeDB!
Identity: abc123def456...

Current people (0):
(none yet)

Commands:
<name> - Add a person with that name
list - Show all people
hello - Greet everyone (check server logs)
Ctrl+C - Quit

> Alice
> [Added] Alice

> Bob
> [Added] Bob

> list
> People in database:

- Alice
- Bob

> hello
> Called say_hello reducer (check server logs)

````
</StepCode>
</Step>

<Step title="Understand the client code">
<StepText>
Open `src/main.ts` to see the Deno client. It uses `DbConnection.builder()` to connect to SpacetimeDB, subscribes to tables, and sets up the interactive CLI using Deno's native APIs.

Unlike browser apps, Deno stores the authentication token in a file using `Deno.readTextFile()` and `Deno.writeTextFile()`.
</StepText>
<StepCode>
```typescript
import { DbConnection } from './module_bindings/index.ts';

// Build and establish connection
DbConnection.builder()
.withUri(HOST)
.withModuleName(DB_NAME)
.withToken(await loadToken()) // Load saved token from file
.onConnect((conn, identity, token) => {
console.log('Connected! Identity:', identity.toHexString());
saveToken(token); // Save token for future connections

// Subscribe to all tables
conn.subscriptionBuilder()
.onApplied((ctx) => {
// Show current data, start CLI
setupCLI(conn);
})
.subscribeToAllTables();

// Listen for table changes
conn.db.person.onInsert((ctx, person) => {
console.log(`[Added] ${person.name}`);
});
})
.build();
````

</StepCode>

</Step>

<Step title="Test with the SpacetimeDB CLI">
<StepText>
You can also use the SpacetimeDB CLI to call reducers and query your data directly. Changes made via the CLI will appear in your Deno client in real-time.
</StepText>
<StepCode>
```bash
# Call the add reducer to insert a person
spacetime call <database-name> add Charlie

# Query the person table

spacetime sql <database-name> "SELECT \* FROM person"
name

---

"Alice"
"Bob"
"Charlie"

# Call say_hello to greet everyone

spacetime call <database-name> say_hello

# View the module logs

spacetime logs <database-name>
2025-01-13T12:00:00.000000Z INFO: Hello, Alice!
2025-01-13T12:00:00.000000Z INFO: Hello, Bob!
2025-01-13T12:00:00.000000Z INFO: Hello, Charlie!
2025-01-13T12:00:00.000000Z INFO: Hello, World!

````
</StepCode>
</Step>

<Step title="Deno-specific features">
<StepText>
**Permissions:** Deno requires explicit permissions. The template uses `--allow-net` for WebSocket connections, `--allow-read` and `--allow-write` for token persistence, and `--allow-env` for configuration.

**Sloppy imports:** The `--unstable-sloppy-imports` flag is required because the generated module bindings use extensionless imports (Node.js convention), while Deno requires explicit file extensions. This flag enables Node.js-style module resolution.

**Built-in TypeScript:** Deno runs TypeScript directly without transpilation, making startup faster and eliminating the need for build tools.

**Import maps:** The `deno.json` file defines import maps, allowing you to import `spacetimedb` directly without `npm:` prefix in your code.

**No node_modules:** Deno caches dependencies globally, so there's no `node_modules` folder to manage.
</StepText>
<StepCode>
```bash
# Configure via environment variables
SPACETIMEDB_HOST=ws://localhost:3000 \
SPACETIMEDB_DB_NAME=my-app \
deno task start

# Or run with explicit permissions
deno run --allow-net --allow-read --allow-write --allow-env --unstable-sloppy-imports src/main.ts

# The deno.json configures tasks and imports
cat deno.json
{
"tasks": {
"dev": "deno run --watch --allow-net --allow-read --allow-write --allow-env --unstable-sloppy-imports src/main.ts",
"start": "deno run --allow-net --allow-read --allow-write --allow-env --unstable-sloppy-imports src/main.ts"
},
"imports": {
"spacetimedb": "npm:spacetimedb@1.*"
}
}
````

</StepCode>

</Step>
</StepByStep>

## Next steps

- See the [Chat App Tutorial](/tutorials/chat-app) for a complete example
- Read the [TypeScript SDK Reference](/sdks/typescript) for detailed API docs
5 changes: 5 additions & 0 deletions templates/deno-ts/.template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"description": "Deno TypeScript client and server template",
"client_lang": "typescript",
"server_lang": "typescript"
}
1 change: 1 addition & 0 deletions templates/deno-ts/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
../../licenses/apache2.txt
10 changes: 10 additions & 0 deletions templates/deno-ts/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"tasks": {
"dev": "deno run --watch --allow-net --allow-read --allow-write --allow-env --unstable-sloppy-imports src/main.ts",
"start": "deno run --allow-net --allow-read --allow-write --allow-env --unstable-sloppy-imports src/main.ts",
"spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings --project-path spacetimedb"
},
"imports": {
"spacetimedb": "npm:spacetimedb@1.*"
}
}
15 changes: 15 additions & 0 deletions templates/deno-ts/spacetimedb/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "spacetime-module",
"version": "1.0.0",
"description": "",
"scripts": {
"build": "spacetime build",
"publish": "spacetime publish"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"spacetimedb": "1.*"
}
}
33 changes: 33 additions & 0 deletions templates/deno-ts/spacetimedb/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { schema, table, t } from 'spacetimedb/server';

export const spacetimedb = schema(
table(
{ name: 'person', public: true },
{
name: t.string(),
}
)
);

spacetimedb.init(_ctx => {
// Called when the module is initially published
});

spacetimedb.clientConnected(_ctx => {
// Called every time a new client connects
});

spacetimedb.clientDisconnected(_ctx => {
// Called every time a client disconnects
});

spacetimedb.reducer('add', { name: t.string() }, (ctx, { name }) => {
ctx.db.person.insert({ name });
});

spacetimedb.reducer('say_hello', ctx => {
for (const person of ctx.db.person.iter()) {
console.info(`Hello, ${person.name}!`);
}
console.info('Hello, World!');
});
23 changes: 23 additions & 0 deletions templates/deno-ts/spacetimedb/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* This tsconfig is used for TypeScript projects created with `spacetimedb init
* --lang typescript`. You can modify it as needed for your project, although
* some options are required by SpacetimeDB.
*/
{
"compilerOptions": {
"strict": true,
"skipLibCheck": true,
"moduleResolution": "bundler",
"jsx": "react-jsx",

/* The following options are required by SpacetimeDB
* and should not be modified
*/
"target": "ESNext",
"lib": ["ES2021", "dom"],
"module": "ESNext",
"isolatedModules": true,
"noEmit": true
},
"include": ["./**/*"]
}
Loading
Loading