Warn when trying to access headers in SSG mode (#3021)

* Warn when trying to access headers in SSG mode

* Adds a changeset

* Warn when accessing headers at all + a test
This commit is contained in:
Matthew Phillips 2022-04-07 15:17:05 -04:00 committed by GitHub
parent 42e0e0fa5c
commit 7e9d82d75e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 60 additions and 3 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Warn when attempting to access headers in SSG mode

View file

@ -191,6 +191,7 @@ async function generatePath(
} }
} }
const ssr = isBuildingToSSR(opts.astroConfig);
const url = new URL(origin + pathname); const url = new URL(origin + pathname);
const options: RenderOptions = { const options: RenderOptions = {
legacyBuild: false, legacyBuild: false,
@ -219,13 +220,13 @@ async function generatePath(
const fullyRelativePath = relPath[0] === '.' ? relPath : './' + relPath; const fullyRelativePath = relPath[0] === '.' ? relPath : './' + relPath;
return fullyRelativePath; return fullyRelativePath;
}, },
request: createRequest({ url, headers: new Headers(), logging }), request: createRequest({ url, headers: new Headers(), logging, ssr }),
route: pageData.route, route: pageData.route,
routeCache, routeCache,
site: astroConfig.site site: astroConfig.site
? new URL(astroConfig.base, astroConfig.site).toString() ? new URL(astroConfig.base, astroConfig.site).toString()
: astroConfig.site, : astroConfig.site,
ssr: isBuildingToSSR(opts.astroConfig), ssr,
}; };
let body: string; let body: string;

View file

@ -11,6 +11,7 @@ export interface CreateRequestOptions {
method?: string; method?: string;
body?: RequestBody | undefined; body?: RequestBody | undefined;
logging: LogOptions; logging: LogOptions;
ssr: boolean;
} }
export function createRequest({ export function createRequest({
@ -19,6 +20,7 @@ export function createRequest({
method = 'GET', method = 'GET',
body = undefined, body = undefined,
logging, logging,
ssr
}: CreateRequestOptions): Request { }: CreateRequestOptions): Request {
let headersObj = let headersObj =
headers instanceof Headers headers instanceof Headers
@ -50,5 +52,21 @@ export function createRequest({
}, },
}); });
if(!ssr) {
// Warn when accessing headers in SSG mode
const _headers = request.headers;
const headersDesc = Object.getOwnPropertyDescriptor(request, 'headers') || {};
Object.defineProperty(request, 'headers', {
...headersDesc,
get() {
warn(logging,
'ssg',
`Headers are not exposed in static-site generation (SSG) mode. To enable reading headers you need to set an SSR adapter in your config.`
);
return _headers;
}
})
}
return request; return request;
} }

View file

@ -176,6 +176,7 @@ async function handleRequest(
method: req.method, method: req.method,
body, body,
logging, logging,
ssr: buildingToSSR
}); });
try { try {

View file

@ -114,6 +114,7 @@ export function rollupPluginAstroScanHTML(options: PluginOptions): VitePlugin {
url: new URL(origin + pathname), url: new URL(origin + pathname),
headers: new Headers(), headers: new Headers(),
logging, logging,
ssr: false,
}), }),
mode: 'production', mode: 'production',
origin, origin,

View file

@ -3,6 +3,9 @@ import MainHead from '../components/MainHead.astro';
import Nav from '../components/Nav/index.jsx'; import Nav from '../components/Nav/index.jsx';
import { test as ssrConfigTest } from '@test/static-build-pkg'; import { test as ssrConfigTest } from '@test/static-build-pkg';
let allPosts = await Astro.glob('./posts/*.md'); let allPosts = await Astro.glob('./posts/*.md');
// Note that this just tests a warning
Astro.request.headers;
--- ---
<html> <html>
<head> <head>

View file

@ -6,14 +6,32 @@ function addLeadingSlash(path) {
return path.startsWith('/') ? path : '/' + path; return path.startsWith('/') ? path : '/' + path;
} }
/**
* @typedef {import('../src/core/logger/core').LogMessage} LogMessage
*/
describe('Static build', () => { describe('Static build', () => {
/** @type {import('./test-utils').Fixture} */
let fixture; let fixture;
/** @type {LogMessage[]} */
let logs = [];
before(async () => { before(async () => {
/** @type {import('../src/core/logger/core').LogOptions} */
const logging = {
dest: {
write(chunk) {
logs.push(chunk);
}
},
level: 'warn',
};
fixture = await loadFixture({ fixture = await loadFixture({
root: './fixtures/static build/', root: './fixtures/static build/',
}); });
await fixture.build(); await fixture.build({ logging });
}); });
it('Builds out .astro pages', async () => { it('Builds out .astro pages', async () => {
@ -137,4 +155,14 @@ describe('Static build', () => {
const $ = cheerioLoad(html); const $ = cheerioLoad(html);
expect($('#ssr-config').text()).to.equal('testing'); expect($('#ssr-config').text()).to.equal('testing');
}); });
it('warns when accessing headers', async () => {
let found = false;
for(const log of logs) {
if(log.type === 'ssg' && /[hH]eaders are not exposed in static-site generation/.test(log.args[0])) {
found = true;
}
}
expect(found).to.equal(true, 'Found the log message');
});
}); });