Skip to content

Commit 0ea47e7

Browse files
matthsbenmccann
authored andcommitted
[feat] expose handler to allow use in custom server
1 parent 02f7aba commit 0ea47e7

File tree

8 files changed

+96
-24
lines changed

8 files changed

+96
-24
lines changed

documentation/faq/80-integrations.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ Put the code to query your database in [endpoints](/docs#routing-endpoints) - do
6767

6868
### How do I use middleware?
6969

70-
In dev, you can add middleware to Vite by using a Vite plugin. For example:
70+
You can add middleware to `adapter-node` for production mode. In dev, you can add middleware to Vite by using a Vite plugin. For example:
7171

7272
```js
7373
const myPlugin = {

packages/adapter-node/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,35 @@ HOST=127.0.0.1 PORT=4000 node build
4545

4646
You can specify different environment variables if necessary using the `env` option.
4747

48+
## Middleware
49+
50+
The adapter exports a middleware `(req, res, next) => {}` that's compatible with [Express](https://github.com/expressjs/expressjs.com) / [Polka](https://github.com/lukeed/polka). Additionally, it also exports a reference server implementation using this middleware with a plain Node HTTP server.
51+
52+
But you can use your favorite server framework to combine it with other middleware and server logic. You can import `createHandler()`, your ready-to-use SvelteKit bundle as middleware, from `./build/handler.js`.
53+
54+
```
55+
import { createHandler } from './build/handler.js';
56+
import express from 'express';
57+
58+
const app = express();
59+
60+
var myMiddleware = function (req, res, next) {
61+
console.log('Hello world!');
62+
next();
63+
};
64+
65+
app.use(myMiddleware);
66+
67+
app.get('/no-svelte', (req, res) => {
68+
res.send('This is not Svelte!')
69+
});
70+
71+
// SvelteKit
72+
app.get('*', createHandler());
73+
74+
app.listen(3000)
75+
```
76+
4877
## Advanced Configuration
4978

5079
### esbuild

packages/adapter-node/index.js

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export default function ({
4141
await compress(static_directory);
4242
}
4343

44-
utils.log.minor('Building server');
44+
utils.log.minor('Building SvelteKit request handler');
4545
const files = fileURLToPath(new URL('./files', import.meta.url));
4646
utils.copy(files, '.svelte-kit/node');
4747
writeFileSync(
@@ -54,10 +54,11 @@ export default function ({
5454
port_env
5555
)}] || (!path && 3000);`
5656
);
57+
5758
/** @type {BuildOptions} */
5859
const defaultOptions = {
59-
entryPoints: ['.svelte-kit/node/index.js'],
60-
outfile: join(out, 'index.js'),
60+
entryPoints: ['.svelte-kit/node/handler.js'],
61+
outfile: join(out, 'handler.js'),
6162
bundle: true,
6263
external: Object.keys(JSON.parse(readFileSync('package.json', 'utf8')).dependencies || {}),
6364
format: 'esm',
@@ -71,6 +72,32 @@ export default function ({
7172
const buildOptions = esbuildConfig ? await esbuildConfig(defaultOptions) : defaultOptions;
7273
await esbuild.build(buildOptions);
7374

75+
utils.log.minor('Building SvelteKit reference server');
76+
/** @type {BuildOptions} */
77+
const defaultOptionsRefServer = {
78+
entryPoints: ['.svelte-kit/node/index.js'],
79+
outfile: join(out, 'index.js'),
80+
bundle: true,
81+
external: ['./handler.js'], // does not work, eslint does not exclude handler from target
82+
format: 'esm',
83+
platform: 'node',
84+
target: 'node12',
85+
// external exclude workaround, see https://github.com/evanw/esbuild/issues/514
86+
plugins: [
87+
{
88+
name: 'fix-handler-exclude',
89+
setup(build) {
90+
// Match an import called "./handler.js" and mark it as external
91+
build.onResolve({ filter: /^\.\/handler\.js$/ }, () => ({ external: true }));
92+
}
93+
}
94+
]
95+
};
96+
const buildOptionsRefServer = esbuildConfig
97+
? await esbuildConfig(defaultOptionsRefServer)
98+
: defaultOptionsRefServer;
99+
await esbuild.build(buildOptionsRefServer);
100+
74101
utils.log.minor('Prerendering static pages');
75102
await utils.prerender({
76103
dest: `${out}/prerendered`

packages/adapter-node/rollup.config.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,16 @@ import commonjs from '@rollup/plugin-commonjs';
33
import json from '@rollup/plugin-json';
44

55
export default [
6+
{
7+
input: 'src/handler.js',
8+
output: {
9+
file: 'files/handler.js',
10+
format: 'esm',
11+
sourcemap: true
12+
},
13+
plugins: [nodeResolve(), commonjs(), json()],
14+
external: ['../output/server/app.js', ...require('module').builtinModules]
15+
},
616
{
717
input: 'src/index.js',
818
output: {
@@ -11,7 +21,7 @@ export default [
1121
sourcemap: true
1222
},
1323
plugins: [nodeResolve(), commonjs(), json()],
14-
external: ['../output/server/app.js', './env.js', ...require('module').builtinModules]
24+
external: ['./handler.js', './env.js', ...require('module').builtinModules]
1525
},
1626
{
1727
input: 'src/shims.js',
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// TODO hardcoding the relative location makes this brittle
2+
import { init, render } from '../output/server/app.js'; // eslint-disable-line import/no-unresolved
3+
import { createPolkaHandler } from './polka-handler.js';
4+
5+
export function createHandler() {
6+
init();
7+
return createPolkaHandler({ render });
8+
}

packages/adapter-node/src/index.js

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,12 @@
1-
// TODO hardcoding the relative location makes this brittle
2-
// @ts-ignore
3-
import { init, render } from '../output/server/app.js';
41
// @ts-ignore
52
import { path, host, port } from './env.js';
6-
import { createServer } from './server';
7-
8-
init();
9-
10-
const instance = createServer({ render });
3+
import { createHandler } from './handler.js';
4+
import { createServer } from 'http';
115

6+
const server = createServer(createHandler());
127
const listenOpts = { path, host, port };
13-
instance.listen(listenOpts, () => {
8+
server.listen(listenOpts, () => {
149
console.log(`Listening on ${path ? path : host + ':' + port}`);
1510
});
1611

17-
export { instance };
12+
export { server };

packages/adapter-node/src/server.js renamed to packages/adapter-node/src/polka-handler.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ const paths = {
1818

1919
// TODO: type render function from @sveltejs/kit/adapter
2020
// @ts-ignore
21-
export function createServer({ render }) {
21+
export function createPolkaHandler({ render }) {
2222
const prerendered_handler = fs.existsSync(paths.prerendered)
2323
? sirv(paths.prerendered, {
2424
etag: true,
@@ -41,7 +41,7 @@ export function createServer({ render }) {
4141
})
4242
: noop_handler;
4343

44-
const server = polka().use(
44+
const polka_instance = polka().use(
4545
// https://github.com/lukeed/polka/issues/173
4646
// @ts-ignore - nothing we can do about so just ignore it
4747
compression({ threshold: 0 }),
@@ -78,5 +78,5 @@ export function createServer({ render }) {
7878
}
7979
);
8080

81-
return server;
81+
return polka_instance.handler;
8282
}

packages/adapter-node/tests/smoke.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
import { test } from 'uvu';
2-
import { createServer } from '../src/server.js';
2+
import { createPolkaHandler } from '../src/polka-handler.js';
33
import * as assert from 'uvu/assert';
44
import fetch from 'node-fetch';
5+
import { createServer } from 'http';
56

67
const { PORT = 3000 } = process.env;
78
const DEFAULT_SERVER_OPTS = { render: () => {} };
89

910
function startServer(opts = DEFAULT_SERVER_OPTS) {
10-
const server = createServer(opts);
11+
const handler = createPolkaHandler(opts);
12+
1113
return new Promise((fulfil, reject) => {
14+
const server = createServer(handler);
1215
server.listen(PORT, (err) => {
1316
if (err) {
1417
reject(err);
@@ -21,14 +24,14 @@ function startServer(opts = DEFAULT_SERVER_OPTS) {
2124
test('starts a server', async () => {
2225
const server = await startServer();
2326
assert.ok('server started');
24-
server.server.close();
27+
server.close();
2528
});
2629

2730
test('serves a 404', async () => {
2831
const server = await startServer();
2932
const res = await fetch(`http://localhost:${PORT}/nothing`);
3033
assert.equal(res.status, 404);
31-
server.server.close();
34+
server.close();
3235
});
3336

3437
test('responses with the rendered status code', async () => {
@@ -43,7 +46,7 @@ test('responses with the rendered status code', async () => {
4346
});
4447
const res = await fetch(`http://localhost:${PORT}/wow`);
4548
assert.equal(res.status, 203);
46-
server.server.close();
49+
server.close();
4750
});
4851

4952
test('passes through umlaut as encoded path', async () => {
@@ -57,7 +60,7 @@ test('passes through umlaut as encoded path', async () => {
5760
});
5861
const res = await fetch(`http://localhost:${PORT}/%C3%BCber-uns`);
5962
assert.equal(await res.text(), '/%C3%BCber-uns');
60-
server.server.close();
63+
server.close();
6164
});
6265

6366
test.run();

0 commit comments

Comments
 (0)