Skip to content

Linking

Link resources together and access them in a typesafe and secure way.

Resource linking is a feature of SST that allows you to link resources together and access them in a typesafe and secure way.

  1. Create a resource that you want to link to. For example, a bucket.

    const bucket = new sst.aws.Bucket("MyBucket");
  2. Link it to your function or frontend, using the link prop.

    new sst.aws.Nextjs("MyWeb", {
    link: [bucket]
    });
  3. Use the SDK to access the linked resource in a typesafe way.

    app/page.tsx
    import { Resource } from "sst";
    console.log(Resource.MyBucket.name);

Working locally

The above applies to your app deployed through sst deploy. To access linked resources locally you’ll need to be running sst dev.

For the frontends, you’ll need to wrap your frontend in the sst dev command.

Terminal window
sst dev next dev

How it works

At high level when you link a resource to a function or frontend, the following happens:

  1. The function is given permission to access the linked resource.

  2. The links that the resource exposes are injected into the function package.

  3. The types to access these links are generated.


Resource links are injected into your function or frontend package when you run sst dev or sst deploy. But this is done in a slightly different way for both these cases.

Functions

The functions in SST are tree shaken and bundled using esbuild. While bundling, SST injects the resource links into the globalThis.

Frontends

The frontends are not bundled by SST. Instead, when they are built, SST injects the resource links into the process.env object using the prefix SST_RESOURCE_.

This is why when you are running your frontend locally, it needs to be wrapped in the sst dev command.


Generating types

When you run sst dev or sst deploy, SST generates the types to access the linked resources. These are generated in a .sst/types.generated.ts file.

This file is referenced using a sst-env.d.ts in your project root. The sst-env.d.ts should be added when you initialize your app with sst init.