Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/tender-kings-knock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@sveltejs/adapter-netlify': minor
Comment thread
serhalp marked this conversation as resolved.
---

chore!: Migrate to the modern Netlify Functions API

The Netlify adapter now generates "v2" Netlify Functions, which uses modern standards (ESM, Request,
Response) instead of the legacy "Lambda-compatible" or "v1" format. Under the hood, this greatly
simplifies the adapter code and improves maintainability.
Comment thread
teemingc marked this conversation as resolved.
Outdated

For more details on features this unlocks for your SvelteKit app, see
https://developers.netlify.com/guides/migrating-to-the-modern-netlify-functions/.

BREAKING CHANGES:

- `platform.context` is now the [modern Netlify Functions
context](https://docs.netlify.com/build/functions/api/#netlify-specific-context-object)
Comment thread
serhalp marked this conversation as resolved.
Outdated
9 changes: 1 addition & 8 deletions documentation/docs/25-build-and-deploy/80-adapter-netlify.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,7 @@ You may build your app using functionality provided directly by SvelteKit withou

### `_headers` and `_redirects`

The [`_headers`](https://docs.netlify.com/routing/headers/#syntax-for-the-headers-file) and [`_redirects`](https://docs.netlify.com/routing/redirects/redirect-options/) files specific to Netlify can be used for static asset responses (like images) by putting them into the project root folder.

### Redirect rules

During compilation, redirect rules are automatically appended to your `_redirects` file. (If it doesn't exist yet, it will be created.) That means:

- `[[redirects]]` in `netlify.toml` will never match as `_redirects` has a [higher priority](https://docs.netlify.com/routing/redirects/#rule-processing-order). So always put your rules in the [`_redirects` file](https://docs.netlify.com/routing/redirects/#syntax-for-the-redirects-file).
- `_redirects` shouldn't have any custom "catch all" rules such as `/* /foobar/:splat`. Otherwise the automatically appended rule will never be applied as Netlify is only processing [the first matching rule](https://docs.netlify.com/routing/redirects/#rule-processing-order).
The [`_headers`](https://docs.netlify.com/routing/headers/#syntax-for-the-headers-file) and [`_redirects`](https://docs.netlify.com/routing/redirects/redirect-options/) files specific to Netlify can be used for static asset responses (like images) by putting them into the project root folder. You can also use [`[[redirects]]`](https://docs.netlify.com/routing/redirects/#syntax-for-the-netlify-configuration-file) in your `netlify.toml`.

### Netlify Forms

Expand Down
38 changes: 8 additions & 30 deletions packages/adapter-netlify/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @import { BuildOptions } from 'esbuild' */
import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve, posix } from 'node:path';
import { join, resolve, posix } from 'node:path';
import { fileURLToPath } from 'node:url';
import { builtinModules } from 'node:module';
import process from 'node:process';
Expand Down Expand Up @@ -241,8 +241,6 @@ async function generate_edge_functions({ builder }) {
function generate_lambda_functions({ builder, publish, split }) {
builder.mkdirp('.netlify/functions-internal/.svelte-kit');

/** @type {string[]} */
const redirects = [];
builder.writeServer('.netlify/server');

const replace = {
Expand All @@ -251,9 +249,6 @@ function generate_lambda_functions({ builder, publish, split }) {

builder.copy(files, '.netlify', { replace, filter: (name) => !name.endsWith('edge.js') });

// Configuring the function to use ESM as the output format.
const fn_config = JSON.stringify({ config: { nodeModuleFormat: 'esm' }, version: 1 });

builder.log.minor('Generating serverless functions...');

if (split) {
Expand Down Expand Up @@ -302,58 +297,46 @@ function generate_lambda_functions({ builder, publish, split }) {
routes
});

const fn = `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`;
const fn = `import { init } from '../serverless.js';\n\nexport default init(${manifest});\n\nexport const config = {\n\tpath: "${pattern}",\n\tpreferStatic: true\n};\n`;

writeFileSync(`.netlify/functions-internal/${name}.mjs`, fn);
writeFileSync(`.netlify/functions-internal/${name}.json`, fn_config);
if (builder.hasServerInstrumentationFile?.()) {
builder.instrument?.({
entrypoint: `.netlify/functions-internal/${name}.mjs`,
instrumentation: '.netlify/server/instrumentation.server.js',
start: `.netlify/functions-start/${name}.start.mjs`,
module: {
exports: ['handler']
exports: ['default']
}
});
}

const redirect = `/.netlify/functions/${name} 200`;
redirects.push(`${pattern} ${redirect}`);
redirects.push(`${pattern === '/' ? '' : pattern}/__data.json ${redirect}`);
}
} else {
const manifest = builder.generateManifest({
relativePath: '../server'
});

const fn = `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`;
const fn = `import { init } from '../serverless.js';\n\nexport default init(${manifest});\n\nexport const config = {\n\tpath: "/*",\n\tpreferStatic: true\n};\n`;

writeFileSync(`.netlify/functions-internal/${FUNCTION_PREFIX}render.json`, fn_config);
writeFileSync(`.netlify/functions-internal/${FUNCTION_PREFIX}render.mjs`, fn);
if (builder.hasServerInstrumentationFile?.()) {
builder.instrument?.({
entrypoint: `.netlify/functions-internal/${FUNCTION_PREFIX}render.mjs`,
instrumentation: '.netlify/server/instrumentation.server.js',
start: `.netlify/functions-start/${FUNCTION_PREFIX}render.start.mjs`,
module: {
exports: ['handler']
exports: ['default']
}
});
}

redirects.push(`* /.netlify/functions/${FUNCTION_PREFIX}render 200`);
}

// this should happen at the end, after builder.writeClient(...),
// so that generated redirects are appended to custom redirects
// rather than replaced by them
builder.log.minor('Writing redirects...');
const redirects_file = join(publish, '_redirects');
// Copy user's custom _redirects file if it exists
if (existsSync('_redirects')) {
builder.log.minor('Copying user redirects...');
const redirects_file = join(publish, '_redirects');
builder.copy('_redirects', redirects_file);
}
builder.mkdirp(dirname(redirects_file));
appendFileSync(redirects_file, `\n\n${redirects.join('\n')}`);
}

function get_netlify_config() {
Expand All @@ -378,11 +361,6 @@ function get_publish_directory(netlify_config, builder) {
return;
}

if (netlify_config.redirects) {
throw new Error(
"Redirects are not supported in netlify.toml. Use _redirects instead. For more details consult the readme's troubleshooting section."
);
}
if (resolve(netlify_config.build.publish) === process.cwd()) {
throw new Error(
'The publish directory cannot be set to the site root. Please change it to another value such as "build" in netlify.toml.'
Expand Down
4 changes: 1 addition & 3 deletions packages/adapter-netlify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@
},
"dependencies": {
"@iarna/toml": "^2.2.5",
"esbuild": "^0.25.4",
"set-cookie-parser": "^2.6.0"
"esbuild": "^0.25.4"
},
"devDependencies": {
"@netlify/dev": "catalog:",
Expand All @@ -59,7 +58,6 @@
"@sveltejs/kit": "workspace:^",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/node": "catalog:",
"@types/set-cookie-parser": "catalog:",
"rollup": "^4.14.2",
"typescript": "^5.3.3",
"vitest": "catalog:"
Expand Down
31 changes: 0 additions & 31 deletions packages/adapter-netlify/src/headers.js

This file was deleted.

51 changes: 0 additions & 51 deletions packages/adapter-netlify/src/headers.spec.js

This file was deleted.

69 changes: 4 additions & 65 deletions packages/adapter-netlify/src/serverless.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import './shims';
import { Server } from '0SERVER';
import { split_headers } from './headers.js';
import { createReadableStream } from '@sveltejs/kit/node';
import process from 'node:process';

/**
* @param {import('@sveltejs/kit').SSRManifest} manifest
* @returns {import('@netlify/functions').Handler}
* @returns {(request: Request, context: import('@netlify/functions').Context) => Promise<Response>}
*/
export function init(manifest) {
const server = new Server(manifest);
Expand All @@ -17,77 +16,17 @@ export function init(manifest) {
read: (file) => createReadableStream(`.netlify/server/${file}`)
});

return async (event, context) => {
return async (request, context) => {
if (init_promise !== null) {
await init_promise;
init_promise = null;
}

const response = await server.respond(to_request(event), {
return server.respond(request, {
platform: { context },
getClientAddress() {
return /** @type {string} */ (event.headers['x-nf-client-connection-ip']);
return context.ip;
}
});

const partial_response = {
statusCode: response.status,
...split_headers(response.headers)
};

if (!is_text(response.headers.get('content-type'))) {
// Function responses should be strings (or undefined), and responses with binary
// content should be base64 encoded and set isBase64Encoded to true.
// https://github.com/netlify/functions/blob/main/src/function/response.ts
return {
...partial_response,
isBase64Encoded: true,
body: Buffer.from(await response.arrayBuffer()).toString('base64')
};
}

return {
...partial_response,
body: await response.text()
};
};
}

/**
* @param {import('@netlify/functions').HandlerEvent} event
* @returns {Request}
*/
function to_request({ httpMethod, headers, rawUrl, body, isBase64Encoded }) {
/** @type {RequestInit} */
const init = {
method: httpMethod,
headers: new Headers(/** @type {Record<string, string>} */ (headers))
};

if (httpMethod !== 'GET' && httpMethod !== 'HEAD') {
const encoding = isBase64Encoded ? 'base64' : 'utf-8';
init.body = typeof body === 'string' ? Buffer.from(body, encoding) : body;
}

return new Request(rawUrl, init);
}

const text_types = new Set([
'application/xml',
'application/json',
'application/x-www-form-urlencoded',
'multipart/form-data'
]);

/**
* Decides how the body should be parsed based on its mime type
*
* @param {string | undefined | null} content_type The `content-type` header of a request/response.
* @returns {boolean}
*/
function is_text(content_type) {
if (!content_type) return true; // defaults to json
const type = content_type.split(';')[0].toLowerCase(); // get the mime type

return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
}
Original file line number Diff line number Diff line change
@@ -1,39 +1,6 @@
// This is a temporary workaround to be compatible with Netlify's new dev server
// TODO: remove this once we overhaul the Netlify adapter to use Netlify's new serverless function format https://docs.netlify.com/build/functions/get-started/?data-tab=TypeScript#write-a-function

import { handler } from '../../.netlify/functions-internal/sveltekit-render.mjs';

/**
* @param {Request} request
* @param {import('@netlify/functions').HandlerContext} context
*/
export default async function (request, context) {
const [rawUrl, rawQuery] = request.url.split('?');
/** @type {import('@netlify/functions').HandlerEvent} */
const event = {
rawUrl,
rawQuery: rawQuery || '',
headers: Object.fromEntries(request.headers),
httpMethod: request.method,
isBase64Encoded: false,
path: new URL(request.url).pathname,
queryStringParameters: Object.fromEntries(new URL(request.url).searchParams),
body: request.body && (await request.text()),
multiValueHeaders: {},
multiValueQueryStringParameters: null
};
const result = await handler(event, context);
if (result) {
return new Response(result.body, {
status: result.statusCode,
// @ts-ignore
headers: result.headers
});
}

return new Response('Not Found', { status: 404 });
}
export { default } from '../../.netlify/functions-internal/sveltekit-render.mjs';

export const config = {
path: '/*'
path: '/*',
preferStatic: true
};
6 changes: 0 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading