Skip to content

Commit

Permalink
Correct handle directory finds when using base in the Node adapter (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewp authored May 12, 2023
1 parent 0fc026f commit 781f558
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/afraid-suits-talk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/node': patch
---

Fix redirects on directories when using base option
8 changes: 7 additions & 1 deletion packages/integrations/node/src/http-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,13 @@ export function createServer(
// File not found, forward to the SSR handler
handler(req, res);
});

stream.on('directory', () => {
// On directory find, redirect to the trailing slash
const location = req.url + '/';
res.statusCode = 301
res.setHeader('Location', location);
res.end(location);
});
stream.on('file', () => {
forwardError = true;
});
Expand Down
15 changes: 12 additions & 3 deletions packages/integrations/node/test/prerender.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ describe('Prerendering', () => {
before(async () => {
process.env.ASTRO_NODE_AUTOSTART = 'disabled';
fixture = await loadFixture({
base: '/some-base',
root: './fixtures/prerender/',
output: 'server',
adapter: nodejs({ mode: 'standalone' }),
Expand All @@ -32,7 +33,7 @@ describe('Prerendering', () => {
}

it('Can render SSR route', async () => {
const res = await fetch(`http://${server.host}:${server.port}/one`);
const res = await fetch(`http://${server.host}:${server.port}/some-base/one`);
const html = await res.text();
const $ = cheerio.load(html);

Expand All @@ -41,7 +42,7 @@ describe('Prerendering', () => {
});

it('Can render prerendered route', async () => {
const res = await fetch(`http://${server.host}:${server.port}/two`);
const res = await fetch(`http://${server.host}:${server.port}/some-base/two`);
const html = await res.text();
const $ = cheerio.load(html);

Expand All @@ -50,11 +51,19 @@ describe('Prerendering', () => {
});

it('Can render prerendered route with query params', async () => {
const res = await fetch(`http://${server.host}:${server.port}/two?foo=bar`);
const res = await fetch(`http://${server.host}:${server.port}/some-base/two/?foo=bar`);
const html = await res.text();
const $ = cheerio.load(html);

expect(res.status).to.equal(200);
expect($('h1').text()).to.equal('Two');
});

it('Omitting the trailing slash results in a redirect that includes the base', 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/');
});
});

0 comments on commit 781f558

Please sign in to comment.