Getting started

Getting Started

Installation

Templating

If you would like to scaffold a complete full stack application with Triplit, you can use the create command:

npm create triplit-app@latest my-app

You can also use the create command to create a new Triplit project from a template. For example, to create a new Triplit project with a working chat application (opens in a new tab):

npm create triplit-app@latest my-app --template=chat

Existing projects

If you have an existing project, Triplit also provides a CLI for creating and managing Triplit projects. Install the CLI in your project:

npm install --save-dev @triplit/cli

All commands in the CLI can be inspected by adding the --help flag. For example, to see the available commands:

triplit --help

Once you have the CLI installed you can initialize a new Triplit project, which will create the necessary files and folders and install the required dependencies:

triplit init

Alternatively, you may manually install the packages you need.

Setting up your client

A Triplit Client instance will set up a local database for your data and (if turned on) will set up the required network connections for syncing. The specifics of your local database and syncing can be configured by passing in options to the client, which are described in the client options reference. For now we will not pass in any options, which will just set up an in-memory local database.

import { TriplitClient } from '@triplit/client';
 
const client = new TriplitClient();

Triplit organizes your data into collections, which are like tables in a relational database. You can insert, update, and delete entities in a collection. As well, you can execute arbitrary queries on the database and subscribe to changes to query results over time.

For example, you can insert some data into a collection and then query for it.

// Define a query
const completedTodosQuery = client
  .query('todos')
  .where('completed', '=', true)
  .build();
 
// Insert data
await client.insert('todos', { text: 'Buy milk', completed: true });
await client.insert('todos', { text: 'Buy eggs', completed: false });
await client.insert('todos', { text: 'Buy bread', completed: true });
 
// Execute the query
const completedTodos = await client.fetch(completedTodosQuery);
console.log(completedTodos);

You can also subscribe to data changes over time.

// Define a query
const completedTodosQuery = client
  .query('todos')
  .where('completed', '=', true)
  .build();
 
// Subscribe to query result updates
const unsubscribe = client.subscribe(completedTodosQuery, (data) => {
  // do something with data
  console.log(data);
});
 
// Insert data over time
setTimeout(
  () => client.insert('todos', { text: 'Buy milk', completed: true }),
  1000
);
setTimeout(
  () => client.insert('todos', { text: 'Buy eggs', completed: false }),
  2000
);
setTimeout(
  () => client.insert('todos', { text: 'Buy bread', completed: true }),
  3000
);

Framework support

If you are using a framework like React, Svelte, or Vue (coming soon), you can use the Triplit framework bindings to make it easier to work with Triplit in your framework. See frameworks for more information.

Schemas and Typescript

Triplit uses a schema to define the structure of your data. This schema is used to validate your data and to generate typescript types for client methods. Though you can technically define your schema anywhere, we recommend you save it at the ./triplit/schema.ts path in your project folder. If you used one of the initialization commands this file should have been created for you.

You can define a schema for your data like this:

./triplit/schema.ts
import { Schema as S, ClientSchema } from '@triplit/client';
 
export const schema = {
  todos: {
    schema: S.Schema({
      id: S.Id(),
      text: S.String(),
      completed: S.Boolean({ default: false }),
    }),
  },
} satisfies ClientSchema;

And pass it as a parameter to the client constructor:

import { TriplitClient } from '@triplit/client';
import { schema } from './schema.js';
 
const client = new TriplitClient({ schema });

You can extract types from the schema to use in your app:

import { Entity } from '@triplit/client';
import { schema } from './schema';
 
type Todo = Entity<typeof schema, 'todos'>;
 
function TodoComponent({ todo }: { todo: Todo }) {
  return <div>{todo.text}</div>;
}

Read about all the data types and options available in a schema here.

Syncing

So far we've covered how to set up a local database and query it. Triplit provides a powerful sync engine that can be used to sync your data across devices in real-time. You can read more about syncing here.

Syncing in local development

Triplit has a robust local development environment that you can set up with a single command.

triplit dev

This will start a local development server that you can use to test syncing. The development server will automatically load the schema defined at ./triplit/schema.ts.

The default URL for the local development server is http://localhost:6543. It will also generate a Service Token and an Anonymous Token that your client app can use to authorize with the server.

We recommend setting up a .env file in your project to store these.

.env
TRIPLIT_DB_URL=http://localhost:6543
TRIPLIT_SERVICE_TOKEN=generated-by-triplit-dev
TRIPLIT_ANONYMOUS_TOKEN=generated-by-triplit-dev

Then, you can use these environment variables to initialize your client:

import { TriplitClient } from '@triplit/client';
import { schema } from './schema.js';
 
const client = new TriplitClient({
  schema,
  serverUrl: process.env.TRIPLIT_DB_URL,
  token: process.env.TRIPLIT_ANONYMOUS_TOKEN,
});
💡

If you're using a framework like Vite (opens in a new tab) or Next.js (opens in a new tab) you should add additional environmental variables prepended with VITE_ or NEXT_PUBLIC_ respectively for the DB_URL and ANONYMOUS_TOKEN. For example, TRIPLIT_DB_URL would become VITE_TRIPLIT_DB_URL or NEXT_PUBLIC_TRIPLIT_DB_URL.

To test that sync is working, you can open up your App in another browser window and observe the data converging.

Syncing with Triplit Cloud

Triplit Cloud is a managed service that provides a scalable and secure way to sync your data across devices. You can sign up for the waitlist for Triplit Cloud in our Discord (opens in a new tab) with the /waitlist command.

Once you have access to Triplit Cloud, you can create a project. That project will have a unique database host URL, a Service Token and an Anonymous Token. Your client app will use these to authorize with the server.

We recommend setting up a .env file in your project to store these.

.env
TRIPLIT_DB_URL=https://project-id.triplit.io
TRIPLIT_SERVICE_TOKEN=taken-from-triplit-cloud
TRIPLIT_ANONYMOUS_TOKEN=taken-from-triplit-cloud

Then, you can use these environment variables to initialize your client:

import { TriplitClient } from '@triplit/client';
import { schema } from './schema.js';
 
const client = new TriplitClient({
  schema,
  serverUrl: process.env.TRIPLIT_DB_URL,
  token: process.env.TRIPLIT_ANONYMOUS_TOKEN,
});

A Triplit Cloud instance will initially load without a schema. If your client is using a schema you must keep the server schema in sync with it or you will run into bugs and undefined behaviors. First, ensure that TRIPLIT_DB_URL and TRIPLIT_SERVICE_TOKEN are set in your .env file to point to the Triplit Cloud instance. Then use the Triplit CLI to "push" your schema to the server:

triplit schema push
⚠️

Changing the schema of your database can lead to data corruption. Triplit will attempt to detect and prevent these backwards-incompatible schema changes.

For more information on safely updating your schema in a production database, see the schema management guide.

Next steps

This is Triplit in its most basic form - a syncing database for your app with reactive queries and great Typescript support. The rest of these docs will provide more detail on Triplit's database API and guides for building specific applications with it.

Additional resources