arkynChangelogGuides
docs / utilities / with-security-headers

withSecurityHeaders

Added in v3.0.12. The withSecurityHeaders function is a utility for adding a small set of security-related HTTP headers to a Response. It's fully opt-in, nothing else in @arkyn/server calls it automatically, you wrap the responses you want it applied to.

Import

ts

import { withSecurityHeaders } from "@arkyn/server/withSecurityHeaders";
Learn how subpath and root imports differ in How do I use imports.

Parameters

The function accepts the following parameters:

response (required)

The Response object to add headers to. Its headers are mutated in place, the same instance is returned.
Type: Response

overrides (optional)

An object of header names to values. A string value replaces or adds that header; null removes it (useful to opt a default header back out).
Type: Record<string, string | null>

Default headers

  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy and Strict-Transport-Security are deliberately not set by default, both are too app-specific to guess safely: a wrong CSP can break an app's own scripts, and HSTS assumes HTTPS is already correctly configured elsewhere. Add either through overrides if your app needs them.

Usage example

The function returns the same Response instance it was given, with headers added.
Type: Response

typescript

import { Success } from "@arkyn/server/success";
import { withSecurityHeaders } from "@arkyn/server/withSecurityHeaders";
// Apply the defaults
return withSecurityHeaders(new Success("OK", { data }).toResponse());
// Add a Content-Security-Policy, and opt out of X-Frame-Options
return withSecurityHeaders(new Success("OK", { data }).toResponse(), {
"Content-Security-Policy": "default-src 'self'",
"X-Frame-Options": null,
});

Notes

The function mutates and returns the exact Response instance passed in, it does not clone the response. Existing headers, body, status, and statusText are all preserved.
Since this is opt-in, wrap it around every response you want protected, for example in a shared response helper or a framework-level middleware/loader wrapper, rather than expecting it to apply automatically.
Related in Utilities
On this page
    arkyn