### Start Preview Server Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/runtime/node.md After building the project, start the Node.js server preview using the generated output to verify the setup. ```shell pnpm run preview ``` -------------------------------- ### Clone and Build Example Repository Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/runtime/node.md Clone the dedicated example repository to test your Node.js setup. Install dependencies using pnpm and build the project. ```shell git clone https://github.com/etherCorps/sveltekit-og.git cd sveltekit-og/examples/node-build pnpm install pnpm run build ``` -------------------------------- ### Install @sveltejs/adapter-netlify with deno Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/netlify.md Use this command to install the Netlify adapter for SvelteKit when using deno as your package manager. ```shell deno add --dev npm:@sveltejs/adapter-netlify ``` -------------------------------- ### Install SvelteKit Vercel Adapter with Deno Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/vercel.md Use this command to install the Vercel adapter for SvelteKit when using Deno. ```shell deno add --dev npm:@sveltejs/adapter-vercel ``` -------------------------------- ### Install @ethercorps/sveltekit-og Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Install the package using npm or pnpm. ```bash npm install @ethercorps/sveltekit-og # or pnpm add @ethercorps/sveltekit-og ``` -------------------------------- ### Install SvelteKit OG Package Source: https://github.com/ethercorps/sveltekit-og/blob/main/README.md Install the @ethercorps/sveltekit-og package using pnpm. ```bash pnpm install @ethercorps/sveltekit-og ``` -------------------------------- ### Install @sveltejs/adapter-netlify with pnpm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/netlify.md Use this command to install the Netlify adapter for SvelteKit when using pnpm as your package manager. ```shell pnpm i -D @sveltejs/adapter-netlify ``` -------------------------------- ### Install @sveltejs/adapter-netlify with npm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/netlify.md Use this command to install the Netlify adapter for SvelteKit when using npm as your package manager. ```shell npm i -D @sveltejs/adapter-netlify ``` -------------------------------- ### Install SvelteKit Adapter Node with Deno Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/node.md Use this command to install the Node adapter if you are using Deno and want to add it as a dependency. ```shell deno add --dev npm:@sveltejs/adapter-node ``` -------------------------------- ### GET /og/+server.ts Example Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/utilities/types.md Example of how to use ImageResponse in a SvelteKit server route to generate a dynamic Open Graph image. ```APIDOC ## GET /og/+server.ts ### Description This example demonstrates how to create a dynamic Open Graph image using the `ImageResponse` class within a SvelteKit server route. ### Method GET ### Endpoint `/og` ### Request Example ```typescript import { ImageResponse } from '@ethercorps/sveltekit-og'; import { CustomFont, resolveFonts } from '@ethercorps/sveltekit-og/fonts'; import MySvelteComponent from '$lib/og/MySvelteComponent.svelte'; export const GET = async () => { const props = { title: 'Dynamic Title', subtitle: 'Generated with Sveltekit OG' }; const fonts = [ new CustomFont( 'Inter', () => fetch('https://example.com/fonts/Inter-Regular.ttf').then((res) => res.arrayBuffer()), { weight: '400' } ) ]; return new ImageResponse( // 1. Svelte Component or Raw HTML MySvelteComponent, // 2. Options { width: 1200, height: 630, fonts: await resolveFonts(fonts) }, // 3. Svelte Component props props ); }; ``` ### Response #### Success Response (200) Returns a `Response` object with the image content. The `Content-Type` header will be set appropriately (e.g., `image/png`). #### Response Example (Binary image data) ``` -------------------------------- ### Install SvelteKit Adapter for Cloudflare with Deno Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/cloudflare.md Use this command to install the Cloudflare adapter as a development dependency when using Deno. ```shell deno add --dev npm:@sveltejs/adapter-cloudflare ``` -------------------------------- ### Start SvelteKit development server Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/README.md Run `npm run dev` to start the development server. Use the `-- --open` flag to automatically open the application in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Install SvelteKit Adapter Node with npm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/node.md Use this command to install the Node adapter if you are using npm as your package manager. ```shell npm i -D @sveltejs/adapter-node ``` -------------------------------- ### Start Svelte Development Server Source: https://github.com/ethercorps/sveltekit-og/blob/main/examples/vercel-build/README.md Run this command to start the development server. The `-- --open` flag will automatically open your application in a new browser tab. ```bash npm run dev ``` ```bash npm run dev -- --open ``` -------------------------------- ### Install @sveltejs/adapter-netlify with yarn Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/netlify.md Use this command to install the Netlify adapter for SvelteKit when using yarn as your package manager. ```shell yarn add -D @sveltejs/adapter-netlify ``` -------------------------------- ### Install SvelteKit Adapter Node with yarn Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/node.md Use this command to install the Node adapter if you are using yarn as your package manager. ```shell yarn add -D @sveltejs/adapter-node ``` -------------------------------- ### Install sveltekit-og with pnpm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-og.md Use this command to install the sveltekit-og package if you are using pnpm as your package manager. ```shell pnpm i @ethercorps/sveltekit-og ``` -------------------------------- ### Install SvelteKit Adapter Node with pnpm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/node.md Use this command to install the Node adapter if you are using pnpm as your package manager. ```shell pnpm i -D @sveltejs/adapter-node ``` -------------------------------- ### Install sveltekit-og with yarn Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-og.md Use this command to install the sveltekit-og package if you are using yarn as your package manager. ```shell yarn add @ethercorps/sveltekit-og ``` -------------------------------- ### Install sveltekit-og with npm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-og.md Use this command to install the sveltekit-og package if you are using npm as your package manager. ```shell npm i @ethercorps/sveltekit-og ``` -------------------------------- ### Install SvelteKit Adapter for Deno with Deno Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/deno.md Use this command to install the SvelteKit adapter for Deno when using Deno's built-in package management. ```shell deno add --dev npm:svelte-adapter-deno ``` -------------------------------- ### Install SvelteKit Adapter for Deno with npm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/deno.md Use this command to install the SvelteKit adapter for Deno when using npm as your package manager. ```shell npm i -D svelte-adapter-deno ``` -------------------------------- ### Install sveltekit-og with deno Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-og.md Use this command to install the sveltekit-og package if you are using deno and want to add it as an npm dependency. ```shell deno add npm:@ethercorps/sveltekit-og ``` -------------------------------- ### Install SvelteKit Adapter for Deno with pnpm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/deno.md Use this command to install the SvelteKit adapter for Deno when using pnpm as your package manager. ```shell pnpm i -D svelte-adapter-deno ``` -------------------------------- ### Install SvelteKit Adapter for Cloudflare with pnpm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/cloudflare.md Use this command to install the Cloudflare adapter as a development dependency when using pnpm. ```shell pnpm i -D @sveltejs/adapter-cloudflare ``` -------------------------------- ### Install SvelteKit Adapter for Cloudflare with npm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/cloudflare.md Use this command to install the Cloudflare adapter as a development dependency when using npm. ```shell npm i -D @sveltejs/adapter-cloudflare ``` -------------------------------- ### Install SvelteKit Adapter for Cloudflare with Yarn Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/cloudflare.md Use this command to install the Cloudflare adapter as a development dependency when using Yarn. ```shell yarn add -D @sveltejs/adapter-cloudflare ``` -------------------------------- ### Install SvelteKit Adapter for Deno with yarn Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/deno.md Use this command to install the SvelteKit adapter for Deno when using yarn as your package manager. ```shell yarn add -D svelte-adapter-deno ``` -------------------------------- ### Example: HTML String Input Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Demonstrates creating an image response using a raw HTML string for the content. ```APIDOC ## Example: HTML String Input ### Description This example shows how to use `ImageResponse` with a simple HTML string to generate an Open Graph image. ### Method `GET` ### Endpoint `/og.png` ### Request Body N/A ### Response #### Success Response (200) - **Content-Type**: `image/png` (or `image/svg+xml` if specified) - **Cache-Control**: `public, immutable, ...` (default one-year) ### Request Example ```typescript // src/routes/og.png/+server.ts import { ImageResponse } from '@ethercorps/sveltekit-og'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { const html = `

@ethercorps/sveltekit-og

Dynamic Open Graph images

`; return new ImageResponse(html, { width: 1200, height: 630 }); }; ``` ``` -------------------------------- ### Install SvelteKit Vercel Adapter with pnpm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/vercel.md Use this command to install the Vercel adapter for SvelteKit when using pnpm as your package manager. ```shell pnpm i -D @sveltejs/adapter-vercel ``` -------------------------------- ### Install SvelteKit Vercel Adapter with npm Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/vercel.md Use this command to install the Vercel adapter for SvelteKit when using npm as your package manager. ```shell npm i -D @sveltejs/adapter-vercel ``` -------------------------------- ### Install SvelteKit Vercel Adapter with Yarn Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/lib/components/add-ons/packages/sveltekit-adapter/vercel.md Use this command to install the Vercel adapter for SvelteKit when using Yarn as your package manager. ```shell yarn add -D @sveltejs/adapter-vercel ``` -------------------------------- ### OG Image Configuration File Example Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/examples/auto-generate-routes.md Create a `sveltekit.og.ts` file in your route directory to define the props for your OG image Svelte component. This file acts as the configuration layer. ```typescript // This file acts as the configuration layer, defining the image's props. /** * The 'ogMetadata' object is exported and its properties are used directly * as props for the ShadcnOG Svelte component. */ export const ogMetadata = { title: 'About SvelteKit OG and Our Team', description: 'Learn about the mission, the architecture, and the contributors to this project.' // You could add other custom props here if your Svelte component accepts them: // icon: 'gear', }; ``` -------------------------------- ### Example: Svelte Component Input with Props Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Illustrates using a Svelte component as the element for ImageResponse, passing dynamic props to it. ```APIDOC ## Example: Svelte Component Input with Props ### Description This example demonstrates using a Svelte component (`BlogCard`) with `ImageResponse`, passing data as props to the component. ### Method `GET` ### Endpoint `/blog/[slug]/og.png` ### Parameters #### Path Parameters - **slug** (`string`) - Required - The unique identifier for the blog post. ### Request Body N/A ### Response #### Success Response (200) - **Content-Type**: `image/png` (or `image/svg+xml` if specified) - **Cache-Control**: `public, immutable, no-transform, max-age=31536000` (automatic cache) ### Request Example ```typescript // src/routes/blog/[slug]/og.png/+server.ts import { ImageResponse } from '@ethercorps/sveltekit-og'; import { GoogleFont, resolveFonts } from '@ethercorps/sveltekit-og/fonts'; import type { RequestHandler } from '@sveltejs/kit'; import BlogCard from '$lib/og/BlogCard.svelte'; const fonts = [ new GoogleFont('Inter', { weight: 400 }), new GoogleFont('Inter', { weight: 700 }) ]; export const GET: RequestHandler = async ({ params }) => { const post = await getPostBySlug(params.slug); // your data fetching return new ImageResponse( BlogCard, { width: 1200, height: 630, fonts: await resolveFonts(fonts), debug: false }, { title: post.title, author: post.author, category: post.category } ); }; ``` ``` -------------------------------- ### OG Image Component Example Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/examples/pre-render.md A simple Svelte component template for generating OG images with inline styles and dynamic property logic. ```svelte

{title}

{version}

``` -------------------------------- ### Pre-render OG Image at Build Time Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Set `prerender = true` in your `+server.ts` route to generate the OG image at build time. This serves the image as a static asset, eliminating serverless cold starts. ```typescript // src/routes/about/og.png/+server.ts import { ImageResponse } from '@ethercorps/sveltekit-og'; import { GoogleFont, resolveFonts } from '@ethercorps/sveltekit-og/fonts'; import AboutCard from '$lib/og/AboutCard.svelte'; import type { RequestHandler } from './$types'; export const prerender = true; // Built once at deploy time const fonts = [new GoogleFont('Inter', { weight: 400 }), new GoogleFont('Inter', { weight: 700 })]; export const GET: RequestHandler = async () => { return new ImageResponse( AboutCard, { width: 1200, height: 630, fonts: await resolveFonts(fonts), headers: { 'Cache-Control': 'public, immutable, max-age=31536000' } }, { title: 'About Our Project', description: 'Learn more about us.' } ); }; ``` -------------------------------- ### Generate Dynamic Image with ImageResponse Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/utilities/types.md Example of returning an ImageResponse from a SvelteKit server route. It demonstrates how to define component props, load custom fonts using utilities, and pass these to the ImageResponse constructor along with component and options. ```typescript import { ImageResponse } from '@ethercorps/sveltekit-og'; import { CustomFont, resolveFonts } from '@ethercorps/sveltekit-og/fonts'; import MySvelteComponent from '$lib/og/MySvelteComponent.svelte'; export const GET = async () => { const props = { title: 'Dynamic Title', subtitle: 'Generated with Sveltekit OG' }; const fonts = [ new CustomFont( 'Inter', () => fetch('https://example.com/fonts/Inter-Regular.ttf').then((res) => res.arrayBuffer()), { weight: '400' } ) ]; return new ImageResponse( // 1. Svelte Component or Raw HTML MySvelteComponent, // 2. Options { width: 1200, height: 630, fonts: await resolveFonts(fonts) }, // 3. Svelte Component props props ); }; ``` -------------------------------- ### Svelte Component with Vanilla CSS for OG Image Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/usage/svelte.md An example of a Svelte component using standard CSS within a ` ``` -------------------------------- ### Pre-rendering Dynamic OG Images with `entries` Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Implement the `entries` function to pre-render dynamic OG images for routes like blog posts. The `GET` handler will execute for each entry during the build process to generate static image files. ```typescript // src/routes/docs/[...slug]/og.png/+server.ts import { ImageResponse } from '@ethercorps/sveltekit-og'; import { GoogleFont, resolveFonts } from '@ethercorps/sveltekit-og/fonts'; import DocCard from '$lib/og/DocCard.svelte'; import type { EntryGenerator, RequestHandler } from './$types'; import { getAllDocs, getDocMetadata } from '$lib/utils/docs.js'; const fonts = [ new GoogleFont('Geist', { weight: 400 }), new GoogleFont('Geist', { weight: 600 }), new GoogleFont('Geist Mono', { weight: 400 }) ]; export const prerender = true; // Tells SvelteKit which dynamic paths to build export const entries: EntryGenerator = async () => { return getAllDocs().map((doc) => ({ slug: doc.slug })); }; export const GET: RequestHandler = async ({ params }) => { const metadata = getDocMetadata(params.slug); if (!metadata) { return new Response(null, { status: 404 }); } const resolvedFonts = await resolveFonts(fonts); // Cached after first call return new ImageResponse( DocCard, { height: 630, width: 1200, fonts: resolvedFonts, headers: { 'Cache-Control': 'public, immutable, max-age=31536000' } }, { title: metadata.title ?? 'Documentation', description: metadata.description ?? '' } ); }; ``` -------------------------------- ### Deno Asset Import Error Example Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/runtime/deno.md Illustrates a common 'NotFound' error in Deno Deploy when using Vite URL imports for assets like fonts. This indicates an issue with how Deno handles asset paths during the build or runtime. ```typescript import imagePath from '$lib/assets/JetBrainsMono-Regular.ttf?url'; or; import imagePath from '$lib/assets/JetBrainsMono-Regular.ttf'; ``` ```shell NotFound: No such file or directory (os error 2): open '_app/immutable/assets/JetBrainsMono-Regular.Dh36KTnx.ttf' at Object.openSync (ext:deno_fs/30_fs.js:543:15) at read (file:///app/src/.deno-deploy/handler.ts:55:25) at wrapped_read (file:///app/src/.deno-deploy/server/index.js:4390:24) at read (file:///app/src/.deno-deploy/server/entries/endpoints/_server.ts.js:142:25) at CustomFont.weight [as input] (file:///app/src/.deno-deploy/server/entries/endpoints/_server.ts.js:154:42) at fallback (file:///app/src/.deno-deploy/server/entries/endpoints/_server.ts.js:40:74) at eventLoopTick (ext:core/01_core.js:179:7) at async file:///app/src/.deno-deploy/server/entries/endpoints/_server.ts.js:97:24 at async Promise.all (index 0) at async resolveFonts (file:///app/src/.deno-deploy/server/entries/endpoints/_server.ts.js:96:25) ``` -------------------------------- ### Generate Image Response with VNode Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Example of using the VNode interface directly to construct an image response in a SvelteKit GET handler. Ensure VNode is stringified when passed to ImageResponse. ```typescript // src/routes/og/+server.ts — using VNode directly (low-level) import { ImageResponse } from '@ethercorps/sveltekit-og'; import type { VNode } from '@ethercorps/sveltekit-og'; const node: VNode = { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%', height: '100%', backgroundColor: '#ffffff' }, children: [ { type: 'h1', props: { style: { fontSize: '72px', color: '#111827', fontWeight: '700' }, children: 'Hello from VNode' } } ] } }; export const GET = async () => { // Pass the serialized VNode as a JSON string, or use it through the satori HTML path return new ImageResponse(JSON.stringify(node), { width: 1200, height: 630 }); }; ``` -------------------------------- ### Create a new SvelteKit project Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/README.md Use `npx sv create` to initialize a new SvelteKit project. You can create it in the current directory or specify a project name. ```bash npx sv create # create a new project in my-app npx sv create my-app ``` -------------------------------- ### Build SvelteKit project for production Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/README.md Execute `npm run build` to generate a production-ready build of your SvelteKit application. Preview the build with `npm run preview`. ```bash npm run build ``` -------------------------------- ### Create a New Svelte Project Source: https://github.com/ethercorps/sveltekit-og/blob/main/examples/cf-pages-build/README.md Use this command to initialize a new SvelteKit project. You can create a project in the current directory or specify a directory name. ```bash npm create svelte@latest # create a new project in my-app npm create svelte@latest my-app ``` -------------------------------- ### Build Svelte Project for Production Source: https://github.com/ethercorps/sveltekit-og/blob/main/examples/netlify-build/README.md Execute this command to create a production-ready build of your Svelte application. Preview the build using `npm run preview`. ```bash npm run build ``` -------------------------------- ### Create a New Svelte Project Source: https://github.com/ethercorps/sveltekit-og/blob/main/examples/vercel-build/README.md Use these commands to initialize a new Svelte project. You can create it in the current directory or specify a project name. ```bash npm create svelte@latest ``` ```bash npm create svelte@latest my-app ``` -------------------------------- ### Generate OG Image with HTML String Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Example of creating an Open Graph image using a raw HTML string. This is suitable for static or simple dynamic content. ```typescript // src/routes/og.png/+server.ts — HTML string input import { ImageResponse } from '@ethercorps/sveltekit-og'; import type { RequestHandler } from '@sveltejs/kit'; export const GET: RequestHandler = async () => { const html = `

@ethercorps/sveltekit-og

Dynamic Open Graph images

`; return new ImageResponse(html, { width: 1200, height: 630 }); // Response headers: Content-Type: image/png, Cache-Control: public, immutable, ... }; ``` -------------------------------- ### Configure Rollup Plugin for Node.js (Legacy) Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/runtime/node.md For older versions or specific Rollup setups, configure the rollupWasm plugin with `esmImport: false` within `build.rollupOptions`. This is a deprecated approach for v5. ```typescript import { sveltekit } from '@sveltejs/kit/vite'; import { rollupWasm } from '@ethercorps/sveltekit-og/plugin'; import { defineConfig } from 'vite'; const config = defineConfig({ plugins: [sveltekit()], build: { rollupOptions: { plugins: [ rollupWasm({ esmImport: false // Crucial for reliable Wasm loading in Node.js }) ] } } }); export default config; ``` -------------------------------- ### Configure SvelteKit Deno Adapter Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/runtime/deno.md Set up the svelte-adapter-deno in your svelte.config.js. This is required for Deno Deployments. ```typescript import adapter from 'svelte-adapter-deno'; const config = { ... , kit: { adapter: adapter() }, ... }; export default config; ``` -------------------------------- ### Read Local Asset into ArrayBuffer Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/advanced-usage/local-assets.md For larger assets, use the `?url` suffix with Vite to get the asset's path, then use `$app/server/read` to access its content as an `ArrayBuffer`. This method is suitable for high-resolution images or custom fonts. ```typescript import { ImageResponse } from '@ethercorps/sveltekit-og'; // 1. Import the asset path string using ?url import imagePath from '$lib/assets/large_image.jpg?url'; import { read } from '$app/server'; // 2. Import the server read utility export const GET = async ({ fetch }) => { // 3. Read the content of the asset path using the utility const assetResponse = await read(imagePath); const imageBuffer = await assetResponse.arrayBuffer(); // 4. Convert ArrayBuffer to Base64 for Satori's consumption const base64Image = Buffer.from(imageBuffer).toString('base64'); const mimeType = assetResponse.headers.get('content-type') || 'image/jpeg'; const dataUrl = `data:${mimeType};base64,${base64Image}`; const htmlToRender = `
`; return new ImageResponse(htmlToRender, { width: 1200, height: 630 }); }; ``` -------------------------------- ### Run Lint and Format Checks Source: https://github.com/ethercorps/sveltekit-og/blob/main/CONTRIBUTING.md Use these commands to ensure your code adheres to the project's style guidelines enforced by ESLint and Prettier. ```bash npm run lint npm run format ``` -------------------------------- ### Debug Mode and Custom Headers for OG Images Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Enable `debug: true` to visualize layout guides and disable caching. Use the `headers` option to add custom HTTP response headers, such as identifying the OG generator. ```typescript // src/routes/og/+server.ts import { ImageResponse } from '@ethercorps/sveltekit-og'; import { resolveFonts, GoogleFont } from '@ethercorps/sveltekit-og/fonts'; import MySvelteComponent from '$lib/og/MySvelteComponent.svelte'; export const GET = async ({ url }) => { const isDebug = url.searchParams.has('debug'); const isError = url.searchParams.has('error'); const fonts = [new GoogleFont('Inter', { weight: 400 })]; return new ImageResponse( MySvelteComponent, { width: 1200, height: 630, debug: isDebug, // ?debug → Cache-Control: no-cache, no-store + layout guides emoji: 'blobmoji', // Use Google's Blobmoji set fonts: await resolveFonts(fonts), status: isError ? 404 : 200, statusText: isError ? 'Not Found' : 'OK', headers: { 'X-OG-Generator': '@ethercorps/sveltekit-og' } }, { title: isError ? 'Page Not Found' : 'My Page Title' } ); }; ``` -------------------------------- ### Generate OG Image with Svelte Component and Props Source: https://context7.com/ethercorps/sveltekit-og/llms.txt Example of creating an Open Graph image using a Svelte component and passing dynamic props. This is useful for more complex and data-driven images. Ensure fonts are resolved before passing them to `ImageResponse`. ```typescript // src/routes/blog/[slug]/og.png/+server.ts — Svelte component input with props import { ImageResponse } from '@ethercorps/sveltekit-og'; import { GoogleFont, resolveFonts } from '@ethercorps/sveltekit-og/fonts'; import type { RequestHandler } from '@sveltejs/kit'; import BlogCard from '$lib/og/BlogCard.svelte'; const fonts = [ new GoogleFont('Inter', { weight: 400 }), new GoogleFont('Inter', { weight: 700 }) ]; export const GET: RequestHandler = async ({ params }) => { const post = await getPostBySlug(params.slug); // your data fetching return new ImageResponse( BlogCard, { width: 1200, height: 630, fonts: await resolveFonts(fonts), debug: false }, { title: post.title, author: post.author, category: post.category } ); // Automatic cache: Cache-Control: public, immutable, no-transform, max-age=31536000 }; ``` -------------------------------- ### Create a New Svelte Project Source: https://github.com/ethercorps/sveltekit-og/blob/main/examples/netlify-build/README.md Use this command to create a new Svelte project. You can create it in the current directory or specify a new directory name. ```bash npm create svelte@latest ``` ```bash npm create svelte@latest my-app ``` -------------------------------- ### Load Local Image as ArrayBuffer at Runtime Source: https://context7.com/ethercorps/sveltekit-og/llms.txt For large assets, use Vite's `?url` suffix with SvelteKit's `read()` to load binary files at runtime. Convert to a Base64 data URL for HTML use. ```typescript // src/routes/og.png/+server.ts import { ImageResponse } from '@ethercorps/sveltekit-og'; import { read } from '$app/server'; import bgImagePath from '$lib/assets/background.jpg?url'; export const GET = async () => { const assetResponse = read(bgImagePath); const imageBuffer = await assetResponse.arrayBuffer(); const base64Image = Buffer.from(imageBuffer).toString('base64'); const mimeType = assetResponse.headers.get('content-type') || 'image/jpeg'; const dataUrl = `data:${mimeType};base64,${base64Image}`; const html = `

Overlay Text

`; return new ImageResponse(html, { width: 1200, height: 630 }); }; ``` -------------------------------- ### Configure Netlify Adapter in svelte.config.js Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/runtime/netlify.md Set up the Netlify adapter in your svelte.config.js file. Ensure the adapter is correctly imported and initialized. ```typescript import adapter from 'svelte-adapter-deno'; const config = { ..., kit: { adapter: adapter() }, ... }; export default config; ``` -------------------------------- ### Custom Vite Plugin for OG Route Generation Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/examples/auto-generate-routes.md This plugin scans for `sveltekit.og.ts` files and programmatically writes `+server.ts` files to handle OG image generation. It's intended to be copied into your project. ```typescript import * as fs from 'node:fs/promises'; import * as path from 'node:path'; import type { Plugin, ViteDevServer } from 'vite'; const PLUGIN_NAME = 'vite-plugin-og-route-generator'; const CONFIG_FILE_PATTERN = /^sveltekit\.og\.(ts|js)$/; const SERVER_ROUTE_DIR = 'og.png'; const DEFAULT_ROUTES_DIR = 'src/routes'; const MANIFEST_FILE_PATH_STRING = '.svelte-kit/generated-og-images.json'; // Content to inject into the auto-generated +server.ts file function generateServerRouteContent(): string { // Imports the metadata and calls the central handler return `import { ogMetadata } from "../sveltekit.og.js"; import { createOgImageHandler } from "$lib/og-image.js"; export const prerender = true; export const GET = createOgImageHandler(ogMetadata); `; } // Helper to clean up previously generated files async function initialCleanup(root: string): Promise { // (Omitted cleanup logic for brevity, but this is critical for clean builds) } // Helper to find all sveltekit.og.(ts|js) files async function discoverConfigFiles(root: string): Promise<{ fullPath: string; ext: string }[]> { // (Omitted discovery logic for brevity) return []; } async function generateRoutes(root: string): Promise { const newManifest = { files: [], directories: [] }; const configFiles = await discoverConfigFiles(root); for (const configFile of configFiles) { const routeDir = path.dirname(configFile.fullPath); const serverRouteFileName = `+server${configFile.ext}`; const newServerDirPath = path.join(routeDir, SERVER_ROUTE_DIR); const newServerFilePath = path.join(newServerDirPath, serverRouteFileName); // 1. Create the new directory (e.g., /about/og.png) await fs.mkdir(newServerDirPath, { recursive: true }); // 2. Write the generated content const content = generateServerRouteContent(); await fs.writeFile(newServerFilePath, content, 'utf-8'); console.log(`[${PLUGIN_NAME}] Generated route: ${path.relative(root, newServerFilePath)}`); newManifest.files.push(newServerFilePath); newManifest.directories.push(newServerDirPath); } // (Omitted manifest write logic for brevity) } export function ogRouteGenerator(): Plugin { let root = ''; return { name: PLUGIN_NAME, configResolved(resolvedConfig) { root = resolvedConfig.root; }, // Run generation at the start of the build process and on dev server startup async buildStart() { await initialCleanup(root); await generateRoutes(root); }, // Re-run on file changes for HMR (ViteDevServer required) configureServer(server: ViteDevServer) { // Logic to watch for changes in sveltekit.og.ts files and regenerate routes... // (Omitted HMR logic for brevity) initialCleanup(root).then(() => generateRoutes(root)); } }; } ``` -------------------------------- ### Import Local Image as Base64 Data URL Source: https://github.com/ethercorps/sveltekit-og/blob/main/docs/src/content/advanced-usage/local-assets.md Use the `?inline` suffix with Vite to import local assets directly as Base64 Data URL strings. This is recommended for small images like logos, as it avoids runtime file system access or network requests. ```svelte
Base64 Logo

My Base64 Title

```