Skip to content

Guides

Authentication

Identify users and control who can read and write each document.

On this page

By default, a project’s public key can read and write any document. Before going to production, connect your auth provider and add access rules.

Issue a token on your server

Your backend signs a short-lived token with the project’s secret key and hands it to the client.

server/auth.ts
import { createServerClient } from '@syndra/server';

const syndra = createServerClient({ secretKey: process.env.SYNDRA_SECRET_KEY });

export async function GET(req: Request) {
  const user = await getSessionUser(req);
  if (!user) return new Response('Unauthorized', { status: 401 });

  const token = await syndra.tokens.create({
    userId: user.id,
    claims: { team: user.teamId },
    expiresIn: '1h',
  });
  return Response.json({ token });
}

Pass it to the client

ts
const syndra = createClient({
  project: 'acme-notes',
  publicKey: import.meta.env.SYNDRA_PUBLIC_KEY,
  auth: async () => {
    const res = await fetch('/api/syndra-token');
    return (await res.json()).token;
  },
});

The client calls auth on connect and again shortly before the token expires.

Access rules

Rules live in syndra.config.ts and are matched against the document path:

syndra.config.ts
import { defineConfig } from 'syndra';

export default defineConfig({
  rules: {
    'teams/{teamId}/**': {
      read: ({ auth, params }) => auth.claims.team === params.teamId,
      write: ({ auth, params }) => auth.claims.team === params.teamId,
    },
    'public/**': { read: true, write: false },
  },
});