Getting Started

This guide will help you get up and running with the Asterisms JS SDK Backend quickly.

Installation

Add the SDK Backend package to your project:

npm install @asterisms/sdk-backend @asterisms/common-core

Or with yarn:

yarn add @asterisms/sdk-backend @asterisms/common-core

Environment Setup

Create a .env file in your project root with the following variables:

# Asterisms Configuration
ASTERISMS_DOMAIN=your-asterisms-domain.com
ASTERISMS_BUNDLE_ID=com.example.yourapp
ASTERISMS_SUBDOMAIN=yourapp
ASTERISMS_NAME=Your App
ASTERISMS_TITLE=Your App
ASTERISMS_DESCRIPTION=Your Asterisms Application

# Optional: Product Authorization Key
ASTERISMS_PRODUCT_AUTHORIZATION_KEY=your-product-key

Basic SvelteKit Integration

The most common way to use the SDK Backend is with SvelteKit. Here's a basic setup:

1. Create SDK Instance

Create a file src/lib/sdkInstance.ts:

import { createSvelteKitBackendSDK, type AsterismsSDKProvider } from '@asterisms/sdk-backend';
import { createFetchAdapter } from '@asterisms/sdk';
import { building } from '$app/environment';
import * as dotenv from 'dotenv';

dotenv.config();

let provider: AsterismsSDKProvider | null = null;

export function useAsterismsBackendSDK() {
  if (building) return;
  if (provider) return provider;

  provider = createSvelteKitBackendSDK({
    env: process.env,
    building,
    httpFactory: createFetchAdapter(fetch),
    registrationData: {
      bundleId: 'com.example.yourapp',
      capabilities: ['FRONTEND_WEBSITE'],
      description: 'Your Asterisms Application',
      name: 'Your App',
      subdomain: 'yourapp',
      title: 'Your App'
    }
  });

  return provider;
}

2. Initialize in Hooks

Create or update src/hooks.server.ts:

import { useAsterismsBackendSDK } from '$lib/sdkInstance';
import type { Handle } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
  const provider = useAsterismsBackendSDK();

  if (provider) {
    // Boot the SDK
    await provider.bootSDK();

    // Make SDK available in locals
    event.locals.sdk = provider.sdk;

    // Use the API router for backend endpoints
    if (event.url.pathname.startsWith('/api/asterisms')) {
      return provider.apiRouter(event);
    }
  }

  return resolve(event);
};

3. Use in API Routes

Create an API route src/routes/api/user/+server.ts:

import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';

export const GET: RequestHandler = async ({ locals }) => {
  try {
    const sdk = locals.sdk;
    if (!sdk) {
      return json({ error: 'SDK not initialized' }, { status: 500 });
    }

    // Use authorization service
    const auth = sdk.authorization();
    const user = await auth.getCurrentUser();

    return json({ user });
  } catch (error) {
    console.error('API error:', error);
    return json({ error: 'Internal server error' }, { status: 500 });
  }
};

Basic Express Integration

For non-SvelteKit projects, you can use the SDK with Express:

import express from 'express';
import { getAsterismsBackendSDK } from '@asterisms/sdk-backend';
import { createFetchAdapter } from '@asterisms/sdk-backend';

const app = express();
const PORT = process.env.PORT || 3000;

// Create SDK instance
const sdk = getAsterismsBackendSDK({
  bundleId: 'com.example.yourapp',
  domain: process.env.ASTERISMS_DOMAIN!,
  subdomain: 'yourapp',
  httpServiceAdapterFactory: createFetchAdapter(fetch),
  registrationData: {
    bundleId: 'com.example.yourapp',
    capabilities: ['BACKEND_SERVICE'],
    description: 'Your Backend Service',
    name: 'Your Service',
    subdomain: 'yourapp',
    title: 'Your Service'
  }
});

async function startServer() {
  try {
    // Boot the SDK
    await sdk.boot();
    console.log('SDK initialized successfully');

    // Basic middleware
    app.use(express.json());

    // Health check endpoint
    app.get('/health', (req, res) => {
      res.json({
        status: 'healthy',
        timestamp: new Date().toISOString()
      });
    });

    // Protected endpoint using authorization
    app.get('/api/user', async (req, res) => {
      try {
        const auth = sdk.authorization();
        const user = await auth.getCurrentUser();
        res.json({ user });
      } catch (error) {
        res.status(401).json({ error: 'Unauthorized' });
      }
    });

    // Start server
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

startServer();

Using SDK Services

Once your SDK is initialized, you can use the various services:

Authorization Service

const auth = sdk.authorization();

// Get current user
const user = await auth.getCurrentUser();

// Check permissions
const canRead = await auth.hasPermission('resource.read');

Storage Service

const storage = sdk.storage();

// Upload a file
const uploadedFile = await storage.upload(fileBlob, {
  bucketId: 'my-bucket-id',
  prefix: 'user-uploads/'
});

// Download a file
const fileResponse = await storage.download(externalId, {
  fileName: 'document.pdf'
});

// Get file metadata
const fileData = await storage.getData(externalId);

// Delete a file
const deletedFile = await storage.delete(externalId);

// List files in a bucket
const files = await storage.list({
  bucketId: 'my-bucket-id',
  path: 'user-uploads/'
});

Notification Service

const notifications = sdk.notifications();

// Send notification to account
await notifications.sendToAccount(accountId, {
  sender: 'your-app',
  message: {
    subject: 'Welcome!',
    text: 'Thanks for joining our service',
    html: '<p>Thanks for joining our service</p>',
    urgency: 'NONE'
  },
  account: null,
  directive: 'PREFERRED',
  delivery: {
    schedule: 'IMMEDIATE',
    delay: '0'
  },
  subscriptionKey: null
});

// Send notification to workspace
await notifications.sendToWorkspace(workspaceId, {
  sender: 'your-app',
  message: {
    subject: 'New Update',
    text: 'Check out our latest features',
    html: '<p>Check out our latest features</p>',
    urgency: 'NONE'
  },
  account: null,
  directive: 'PREFERRED',
  delivery: {
    schedule: 'IMMEDIATE',
    delay: '0'
  },
  subscriptionKey: null
});

// Using the helper function for easier notification creation
import { createNotification } from '@asterisms/sdk-backend';

const notification = createNotification({
  sender: 'your-app',
  subject: 'Welcome!',
  text: 'Thanks for joining our service',
  html: '<p>Thanks for joining our service</p>',
  urgency: 'NONE'
});

await notifications.sendToAccount(accountId, notification);

Registration Service

const registration = sdk.registration();

// Get app information
const appInfo = await registration.getAppInfo();

// Register additional capabilities
await registration.updateCapabilities(['BACKEND_SERVICE', 'WEBHOOKS']);

Next Steps

Now that you have the basics set up, explore these topics:

  1. Core Concepts - Understand the architecture
  2. Authentication & Authorization - Implement user auth
  3. Storage Services - Persist application data
  4. Notification Services - Send notifications
  5. API Reference - Complete API documentation
  6. Examples - Working examples and patterns

Common Issues

SDK Not Initializing

If the SDK fails to initialize:

  1. Check your environment variables
  2. Verify your domain and subdomain configuration
  3. Ensure your product authorization key is valid
  4. Check network connectivity to the Asterisms domain

Authentication Errors

If you're getting authentication errors:

  1. Verify your product authorization key
  2. Check that your bundle ID is properly registered
  3. Ensure you're calling bootSDK() before using services

TypeScript Errors

If you're getting TypeScript errors:

  1. Make sure you have the latest types installed
  2. Check that your tsconfig.json includes the SDK types
  3. Verify that you're importing from the correct package paths

For more detailed troubleshooting, see the Troubleshooting Guide.