Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(node): add trailingSlash support #9080

Merged
merged 6 commits into from
Jan 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calm-jobs-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/node': minor
---

Add trailingSlash support to NodeJS adapter
62 changes: 46 additions & 16 deletions packages/integrations/node/src/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path';
import url from 'node:url';
import fs from 'node:fs';
import send from 'send';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Options } from './types.js';
Expand All @@ -18,8 +19,47 @@ export function createStaticHandler(app: NodeApp, options: Options) {
*/
return (req: IncomingMessage, res: ServerResponse, ssr: () => unknown) => {
if (req.url) {
let pathname = app.removeBase(req.url);
pathname = decodeURI(new URL(pathname, 'http://host').pathname);
const [urlPath, urlQuery] = req.url.split('?');
const filePath = path.join(client, app.removeBase(urlPath));

let pathname: string;
let isDirectory = false;
try {
isDirectory = fs.lstatSync(filePath).isDirectory();
} catch {}

const { trailingSlash = 'ignore' } = options;

const hasSlash = urlPath.endsWith('/');
switch (trailingSlash) {
case "never":
if (isDirectory && (urlPath != '/') && hasSlash) {
pathname = urlPath.slice(0, -1) + (urlQuery ? "?" + urlQuery : "");
res.statusCode = 301;
res.setHeader('Location', pathname);
return res.end();
} else pathname = urlPath;
// intentionally fall through
case "ignore":
{
if (isDirectory && !hasSlash) {
pathname = urlPath + "/index.html";
} else
pathname = urlPath;
}
break;
case "always":
if (!hasSlash) {
pathname = urlPath + '/' +(urlQuery ? "?" + urlQuery : "");
res.statusCode = 301;
res.setHeader('Location', pathname);
return res.end();
} else
pathname = urlPath;
break;
}
// app.removeBase sometimes returns a path without a leading slash
pathname = prependForwardSlash(app.removeBase(pathname));

const stream = send(req, pathname, {
root: client,
Expand Down Expand Up @@ -47,20 +87,6 @@ export function createStaticHandler(app: NodeApp, options: Options) {
_res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
});
stream.on('directory', () => {
// On directory find, redirect to the trailing slash
let location: string;
if (req.url!.includes('?')) {
const [url1 = '', search] = req.url!.split('?');
location = `${url1}/?${search}`;
} else {
location = appendForwardSlash(req.url!);
}

res.statusCode = 301;
res.setHeader('Location', location);
res.end(location);
});
stream.on('file', () => {
forwardError = true;
});
Expand All @@ -81,6 +107,10 @@ function resolveClientDir(options: Options) {
return client;
}

function prependForwardSlash(pth: string) {
return pth.startsWith('/') ? pth : '/' + pth;
}

function appendForwardSlash(pth: string) {
return pth.endsWith('/') ? pth : pth + '/';
}
1 change: 1 addition & 0 deletions packages/integrations/node/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { Options } from './types.js';
applyPolyfills();
export function createExports(manifest: SSRManifest, options: Options) {
const app = new NodeApp(manifest);
options.trailingSlash = manifest.trailingSlash;
return {
options: options,
handler:
Expand Down
2 changes: 2 additions & 0 deletions packages/integrations/node/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NodeApp } from 'astro/app/node';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { SSRManifest } from 'astro';

export interface UserOptions {
/**
Expand All @@ -17,6 +18,7 @@ export interface Options extends UserOptions {
server: string;
client: string;
assets: string;
trailingSlash?: SSRManifest['trailingSlash'];
}

export interface CreateServerOptions {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import node from '@astrojs/node'

export default {
base: '/some-base',
output: 'hybrid',
trailingSlash: 'never',
adapter: node({ mode: 'standalone' })
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@test/node-trailingslash",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*",
"@astrojs/node": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Index</h1>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
export const prerender = true;
---
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
</body>
</html>
16 changes: 10 additions & 6 deletions packages/integrations/node/test/prerender.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,14 @@ describe('Prerendering', () => {
expect($('h1').text()).to.equal('Two');
});

it('Omitting the trailing slash results in a redirect that includes the base', async () => {
it('Can render prerendered route without trailing slash', async () => {
const res = await fetch(`http://${server.host}:${server.port}/some-base/two`, {
redirect: 'manual',
});
expect(res.status).to.equal(301);
expect(res.headers.get('location')).to.equal('/some-base/two/');
const html = await res.text();
const $ = cheerio.load(html);
expect(res.status).to.equal(200);
expect($('h1').text()).to.equal('Two');
});
});

Expand Down Expand Up @@ -203,12 +205,14 @@ describe('Hybrid rendering', () => {
expect($('h1').text()).to.equal('One');
});

it('Omitting the trailing slash results in a redirect that includes the base', async () => {
it('Can render prerendered route without trailing slash', async () => {
const res = await fetch(`http://${server.host}:${server.port}/some-base/one`, {
redirect: 'manual',
});
expect(res.status).to.equal(301);
expect(res.headers.get('location')).to.equal('/some-base/one/');
const html = await res.text();
const $ = cheerio.load(html);
expect(res.status).to.equal(200);
expect($('h1').text()).to.equal('One');
});
});

Expand Down