sst / sst

Build modern full-stack applications on AWS

Home Page:https://sst.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SvelteKit build fails due to resource binding

magicalpuffin opened this issue · comments

When building the SvelteKit site, an error will occur even though the resource is correctly bound. This occurs for resources accessed outside of the load part of +page.server.ts even when building using sst bind vite build. The resource can also still be accessed by placing it in a function.

Running in dev works fine, issue shows up when building during deploy.

What is odd is that this issue seems to affect different constructs. Config seems to be bound fine but, other constructs such as Api and RDS have this issue.

I'm fine with using functions or Config as a workaround, but is this behavior intentional?

I created a basic example: https://github.com/magicalpuffin/public-debug/tree/main/2024/sst-svelte-bind

// $lib/myLib.ts
import { Config } from 'sst/node/config';
import { Api } from 'sst/node/api';

// works
export const myConfigObj = { value: Config.MY_CONFIG };
// doesn't work
export const myApiObj = { value: Api.api.url };

// works
export function getMyConfig() {
	return Config.MY_CONFIG;
}
// works
export function getMyApi() {
	return Api.api.url;
}
// MyStack.ts
import { StackContext, Api, SvelteKitSite, Config } from "sst/constructs";

export function API({ stack }: StackContext) {
  const MY_CONFIG = new Config.Parameter(stack, "MY_CONFIG", {
    value: "myconfigvalue",
  });

  stack.setDefaultFunctionProps({ bind: [MY_CONFIG] });
  const api = new Api(stack, "api", {
    routes: {
      "GET /": "packages/functions/src/lambda.handler",
    },
  });

  const site = new SvelteKitSite(stack, "site", {
    bind: [MY_CONFIG, api],
    path: "packages/frontend/",
  });

  stack.addOutputs({
    ApiEndpoint: api.url,
    SiteURL: site.url,
  });
}
node:internal/event_target:1096
  process.nextTick(() => { throw err; });
                           ^
Error: Cannot use Api.api. Please make sure it is bound to this function.
commented

I don't know this specific case but it sounds very similar to this: https://sst.dev/blog/moving-away-from-cdk.html#1-linking-resources

Can you try doing a double deploy? Once without the site, then with it? The workaround for this is to use an environment variable.

Should be fixed in Ion.

Thanks for the reply. I tried deploying twice, first deploying with just the Api, and then with the SvelteKit site. The build worked correctly this time.

This issue seems to match what you described the blog as well. Best of luck to you guys, Ion sounds promising.