Encore JavaScript/TypeScript SDK

1.56.6 · active · verified Tue Apr 21

Encore's JavaScript/TypeScript SDK, currently at stable version 1.56.6, provides the necessary APIs and development utilities for building backend applications within the Encore cloud platform. It enables developers to define services, interact with built-in platform features like caching and secrets, and manage application infrastructure using a declarative, type-safe approach. The SDK integrates seamlessly with the Encore CLI and platform, abstracting away complex infrastructure provisioning. Recent updates include comprehensive built-in support for caching in Encore.ts, powered by Redis, offering various type-safe keyspace types such as `StringKeyspace` and `StructKeyspace`. It also includes internal improvements for Go 1.26 support and enhanced secret management features via the CLI. Releases are frequent, typically focusing on minor fixes, performance enhancements, and new platform feature integrations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining an Encore API service in TypeScript with type-safe caching using a `StringKeyspace` to retrieve and store user data.

import { api, Cache, StringKeyspace } from 'encore.dev';

// Define a type for user data that will be cached
interface UserData {
  id: string;
  name: string;
  email: string;
}

// Declare a type-safe cache keyspace for user data
const userCache = Cache.declare(
  'user_data',
  StringKeyspace<UserData>() // Keys are strings, values are UserData objects
);

// Define an Encore service named 'UserService'
// This service exposes a GET /user/:id API endpoint
export const user = api(
  {
    name: 'UserService',
    endpoint: 'user',
    path: '/user/:id',
    method: 'GET',
  },
  async (id: string): Promise<UserData> => {
    // Try to retrieve user data from the cache first
    const cachedUser = await userCache.get(id);
    if (cachedUser) {
      console.log(`[Encore] User ${id} found in cache.`);
      return cachedUser;
    }

    // If not in cache, simulate fetching from a 'database'
    console.log(`[Encore] Fetching user ${id} from database...`);
    await new Promise(resolve => setTimeout(resolve, 200)); // Simulate async DB call

    const userData: UserData = { 
      id: id, 
      name: `User ${id} Name`, 
      email: `user${id}@example.com` 
    };

    // Store the fetched data in the cache for 5 minutes (300 seconds)
    await userCache.put(id, userData, { ttl: 300 });

    return userData;
  }
);

// To run this, save as user.ts in an Encore application directory
// and execute 'encore run'. The API endpoint will be exposed automatically.

view raw JSON →