Skip to content

Instantly share code, notes, and snippets.

@EnzoAlbornoz
Created November 1, 2023 04:25
Show Gist options
  • Save EnzoAlbornoz/b7a72f4651d404e756e18f8ca9fdde97 to your computer and use it in GitHub Desktop.
Save EnzoAlbornoz/b7a72f4651d404e756e18f8ca9fdde97 to your computer and use it in GitHub Desktop.
NuxtSite for SST@2.32
import fs from "node:fs";
import path from "node:path";
import { SsrSite, type SsrSiteProps } from "sst/constructs/SsrSite.js";
import { AllowedMethods } from "aws-cdk-lib/aws-cloudfront";
type Construct = ConstructorParameters<typeof SsrSite>[0];
export class NuxtSite extends SsrSite {
protected typesPath = "src";
constructor(scope: Construct, id: string, props?: SsrSiteProps) {
super(scope, id, {
...props,
environment: {
...props?.environment,
NITRO_PRESET: "aws_lambda",
},
});
// Enable server to fetch images from bucket
this.serverFunction?.attachPermissions?.([this.bucket, "getObject"]);
}
public getConstructMetadata() {
return {
type: "NuxtSite",
...this.getConstructMetadataBase(),
};
}
protected plan() {
const {
runtime,
timeout,
memorySize,
bind,
nodejs,
permissions,
environment,
cdk,
path: sitePath,
} = this.props;
const publicFolder = path.join(sitePath, ".output", "public");
const fallbackAssets = ["_ipx"];
const publicAssets = fs.readdirSync(publicFolder).map((item) => {
const cacheType = fallbackAssets.includes(item)
? "static"
: "static";
const originName = fallbackAssets.includes(item)
? "fallthroughServer"
: "static";
return {
cacheType,
pattern: fs
.statSync(path.join(sitePath, ".output", "public", item))
.isDirectory()
? `${item}/*`
: item,
origin: originName,
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
} as const;
});
return this.validatePlan({
cloudFrontFunctions: {
serverCfFunction: {
constructId: "CloudFrontFunction",
injections: [
this.useCloudFrontFunctionHostHeaderInjection(),
],
},
},
// TODO: Implement support for Edge functions
edgeFunctions: undefined,
origins: {
server: {
type: "function",
constructId: "ServerFunction",
function: {
bundle: path.join(sitePath, ".output", "server"),
handler: "index.handler",
runtime,
memorySize,
timeout,
nodejs: {
format: "esm",
...nodejs,
},
bind,
environment: {
...environment,
},
permissions,
...cdk?.server,
},
},
static: {
type: "s3",
copy: [
{
from: ".output/public",
to: "",
cached: true,
versionedSubDir: "_nuxt",
},
],
},
fallthroughServer: {
type: "group",
// Try s3 first, then server
primaryOriginName: "static",
fallbackOriginName: "server",
fallbackStatusCodes: [404, 403],
},
},
behaviors: [
// Server as a try catch all
{
cacheType: "server",
cfFunction: "serverCfFunction",
origin: "server",
allowedMethods: AllowedMethods.ALLOW_ALL,
},
// create 1 behaviour for each top level asset file/folder
...publicAssets,
],
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment