Skip to content

Commit

Permalink
fix(server): improve 304 handling
Browse files Browse the repository at this point in the history
closes #178
  • Loading branch information
pi0 committed Oct 17, 2023
1 parent 4690342 commit 06820b5
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
createError,
H3Event,
H3Error,
send,
} from "h3";
import { IPX } from "./ipx";

Expand Down Expand Up @@ -79,18 +80,10 @@ export function createIPXH3Handler(ipx: IPX) {
// Get image meta from source
const sourceMeta = await img.getSourceMeta();

// Caching headers
if (sourceMeta.mtime) {
if (
getRequestHeader(event, "if-modified-since") &&
new Date(getRequestHeader(event, "if-modified-since") || "") >=
sourceMeta.mtime
) {
setResponseStatus(event, 304);
return null;
}
setResponseHeader(event, "last-modified", sourceMeta.mtime.toUTCString());
}
// Send CSP headers to prevent XSS
setResponseHeader(event, "content-security-policy", "default-src 'none'");

// Send Cache-Control header
if (typeof sourceMeta.maxAge === "number") {
setResponseHeader(
event,
Expand All @@ -99,25 +92,37 @@ export function createIPXH3Handler(ipx: IPX) {
);
}

// Get converted image
// Handle modified time if available
if (sourceMeta.mtime) {
// Send Last-Modified header
setResponseHeader(event, "last-modified", sourceMeta.mtime.toUTCString());

// Check for last-modified request header
const _ifModifiedSince = getRequestHeader(event, "if-modified-since");
if (_ifModifiedSince && new Date(_ifModifiedSince) >= sourceMeta.mtime) {
setResponseStatus(event, 304);
return send(event);
}
}

// Process image
const { data, format } = await img.process();

// ETag
// Generate and send ETag header
const etag = getEtag(data);
setResponseHeader(event, "etag", etag);

// Check for if-none-match request header
if (etag && getRequestHeader(event, "if-none-match") === etag) {
setResponseStatus(event, 304);
return null;
return send(event);
}

// Mime
// Content-Type header
if (format) {
setResponseHeader(event, "content-type", `image/${format}`);
}

// Prevent XSS
setResponseHeader(event, "content-security-policy", "default-src 'none'");

return data;
};

Expand Down

0 comments on commit 06820b5

Please sign in to comment.