@lwrjs/security

HTTP security headers guard your site against malicious code injections and cross-site scripting (XSS) attacks. You can implement security headers for your LWR site on a route-by-route basis using the @lwrjs/security package.

@lwrjs/security exposes a default route handler and a security wrapper, both of which apply a set of default security headers. To customize these headers, modify the corresponding header configuration objects.

Usage 

To add this package to your project, run npm install @lwrjs/security on the command line. Implement this package for a route via the default handler or a security wrapper.

Default Route Handler 

The @lwrjs/security route handler matches the RouteHandlerFunction interface.

Default Route Handler Syntax
1type RouteHandler = (ViewRequest, HandlerContext) => Promise<ViewResponse>;

It’s exposed as the default export.

./src/route-handlers/custom.ts
1export { default } from '@lwrjs/security';

To use the default handler for a route, set @lwrjs/security as the route handler in lwr.config.json.

lwr.config.json
1{
2    "routes": [
3        {
4            "id": "home",
5            "path": "/",
6            "rootComponent": "examples/example",
7            "routeHandler": "@lwrjs/security",
8        },
9    ]
10}

To modify a security header in the default route handler, set the corresponding header configuration object in the routeHandler section. You can disable a header by setting its configuration object to false. For more information about default headers and header configuration, skip ahead to Headers.

lwr.config.json
1"routeHandler": ["@lwrjs/security", {
2    "contentSecurityPolicy": "default-src 'self'&semi;base-uri 'self'&semi; script-src 'self'",
3    "referrerPolicy": false,
4    "xXSSProtection": false
5    }]

Security Wrappers 

The @lwrjs/security route handler wrapper secure() applies security headers to an existing route handler. The wrapper is exposed as a named export. It takes a route handler as an argument and returns a promise.

RouteHandlerWrapper syntax
1type RouteHandlerWrapper = (RouteHandlerFunction) => Promise<RouteHandlerReturnType>;

RouteHandlerReturnType can be a ViewResponse or ViewDefinitionResponse. Each type of promise applies headers as follows:

  • ViewDefinitionResponse - applies the default security headers with inline resource hashing.
  • ViewResponse (HTML content) - applies the default security headers without resource hashing.
  • ViewResponse (non-HTML content) - doesn’t apply headers.

For example, this routeHandler.ts file passes the routeHandler into secure(). Since the headers section is empty, only the default headers are used.

routeHandler.ts
1import type { ViewDefinitionResponse } from '@lwrjs/types';
2import { secure } from '@lwrjs/security';
3
4function routeHandler(): ViewDefinitionResponse {
5    return {
6        // programmatically define the view configuration
7        view: {
8            rootComponent: 'example/home'
9        },
10        // set response headers
11        headers: {},
12    };
13}
14
15export default secure(routeHandler);

To modify a header for the default handler, configure the corresponding header configuration object in the route handler file. You can disable a header by setting its configuration object to false.

routeHandler.ts
1headers: {
2    "contentSecurityPolicy": "default-src 'self'&semi;base-uri 'self'&semi; script-src 'self'",
3    "referrerPolicy": false,
4    "xXSSProtection": false
5},

Headers 

The default route handler and security wrapper automatically enable the following security headers.

Content-Security-Policy 

The Content-Security-Policy header directs your site to load content from only approved sources. For a list of acceptable formats for source values, see CSP Source Values.

These are the default directives for the Content-Security-Policy header.

DirectiveDescriptionDefault Source Value
default-srcSet the default source value for all directives that don’t have a value.'self'
base-uriSet approved sources that load content in the page’s <base> element.'self'
font-srcSet approved sources that provide fonts.'self' https: data:;
form-actionSet approved sources that a form can send information to.'self'
frame-ancestorsSet approved sources that can embed your page (the current frame) into a container like <frame> on their site.'self'
img-srcSet approved sources of images and icons.'self' data:;
object-srcSet approved sources of <object> and <embed> elements.'none'
script-srcSet approved sources of JavaScript code for elements like <script>. You can set the value of this directive to a hash, like 'sha256-hash_value'.'self'
script-src-attrSet approved sources of only JavaScript inline event handlers.'none'
style-srcSet approved sources of stylesheets.'self' https: 'unsafe-inline'
upgrade-insecure-requestsWhen this directive is declared in a Content-Security-Policy header, it upgrades HTTP requests (insecure) to HTTPS requests (secure). If an HTTP request is not available as an HTTPS request, the request fails.

Customize the Content-Security-Policy Header 

There are two ways to modify the Content-Security-Policy header.

contentSecurityPolicy
1contentSecurityPolicy?: ContentSecurityPolicy | string | boolean;

You can set contentSecurityPolicy to a ContentSecurityPolicy configuration object that contains your custom directives and options for the header. This object overwrites the default values, so you set the directives from scratch.

Alternatively, you can conveniently set contentSecurityPolicy to a string of directive-value pairs. When your input is a string, useDefault is automatically set to false and resourceHashing is automatically set to true. This overwrites the default values, so you set the directives from scratch.

1// The string:
2"contentSecurityPolicy": "default-src 'self';base-uri 'self'; script-src 'self'"
3
4// is parsed into this ContentSecurityPolicy object:
5"contentSecurityPolicy":
6    {
7        "useDefault": false,
8        "resourceHashing": true,
9        "directives": "default-src 'self';base-uri 'self'; script-src 'self'"
10    }

Cross-Origin-Embedder-Policy 

The Cross-Origin-Embedder-Policy header controls how a page loads cross-origin resources.

The default policy is require-corp. To configure this header, set the crossOriginEmbedderPolicy object to one of the following values in string format.

  • unsafe-none
  • require-corp
  • credentialless

For information about these directives, see MDN Web Docs: Cross-Origin-Embedder-Policy Directives.

Cross-Origin-Opener-Policy 

The Cross-Origin-Opener-Policy header separates a top-level browser instance of a page (like a window) from different page contexts, like pop-ups and other browser tabs.

The default policy is same-origin. To configure this header, set the crossOriginOpenerPolicy object to one of the following values in string format.

  • same-origin
  • same-origin-allow-popups
  • unsafe-none

For information about these directives, see MDN Web Docs: Cross-Origin-Opener-Policy Directives

Example
1"crossOriginOpenerPolicy": "unsafe-none"

Cross-Origin-Resource-Policy 

The Cross-Origin-Resource-Policy header controls whether external websites can access and load content from your site.

The default policy is same-origin. To configure this header, set the crossOriginResourcePolicy object to one of the following values in string format.

  • same-origin
  • same-origin-allow-popups
  • unsafe-none

For information about these directives, see MDN Web Docs: Cross-Origin-Resource-Policy Directives

Example
1"crossOriginResourcePolicy": "unsafe-none"

Origin-Agent-Cluster 

The Origin-Agent-Cluster header controls whether or not the browser creates same-origin groups of pages. For more information about same-origin versus cross-origin pages, see Understanding “same-site” and “same-origin”.

The default value for the originAgentCluster object is the boolean ?1.

Example
1"originAgentCluster": "?1"

For more information about this header and accepted values, see MDN Web Docs: Origin-Agent-Cluster.

Strict-Transport-Security 

The Strict-Transport-Security header forces the browser to access a site with HTTPS. Attempts to access the site with HTTP are automatically converted to HTTPS requests. If an HTTP request is not available as an HTTPS request, the request fails.

These are the default directives for this header.

DirectiveDirective DescriptionDefault Value
max-ageDuration (in seconds) that the browser should only load the site with HTTPS.15552000
includeSubDomainsApplies header settings to all subdomains.

Customize the Strict-Transport-Security Header 

There are two ways to modify the Strict-Transport-Security header.

strictTransportSecurity
1strictTransportSecurity?: StrictTransportSecurity | string | boolean;

You can set strictTransportSecurity to a StrictTransportSecurity configuration object that contains your custom directives and options for the header. This object overwrites the default values, so you set the directives from scratch.

Alternatively, you can conveniently set strictTransportSecurity to a string of directive-value pairs. When your input is a string, it overwrites the default values and only uses your input.

Example
1// The string:
2"strictTransportSecurity": "max-age=15552000&semi; preload"
3
4// is parsed into this StrictTransportSecurity object:
5"strictTransportSecurity":
6    {
7        "maxAge": 15552000,
8        "preload": true
9    }

Referrer-Policy 

The Referrer-Policy header controls what information is shared with different types of browser requests.

The default policy is no-referrer. To configure this header, set the referrerPolicy object to one of the following values in string format.

  • no-referrer
  • no-referrer-when-downgrade
  • origin
  • origin-when-cross-origin
  • same-origin
  • strict-origin
  • strict-origin-when-cross-origin
  • unsafe-url

For information about these directives, see MDN Web Docs: Referrer-Policy Directives

Example
1"referrerPolicy": "same-origin"

X-Content-Type-Options 

The X-Content-Type-Options header controls browser requests based on the request destination type and the MIME type.

The default policy is no-sniff. You can either disable this header or keep the no-sniff configuration.

X-DNS-Prefetch-Control 

The X-DNS-Prefetch-Control header controls DNS prefetching.

The default policy is off, which disables prefetching. To configure this header, set the xDNSPrefetchControl object to one of the following values in string format.

  • off
  • on

For information about these directives, see MDN Web Docs: X-DNS-Prefetch-Control Directives.

X-Download-Options 

The X-Download-Options header controls whether content is executed in the browser or downloaded onto a local machine.

The default policy is "noopen", which prevents content from executing in the browser. You can either disable this header or keep the noopen configuration.

X-Frame-Options 

The X-Frame-Options header determines whether or not the browser can load the page in a frame.

The default value is sameorigin. To configure this header, set the xFrameOptions object to one of the following values in string format.

  • sameorigin
  • deny

For information about these directives, see MDN Web Docs: X-Frame-Options Directives.

X-Permitted-Cross-Domain-Policies 

The X-Permitted-Cross-Domain-Policies header controls how resources are shared with cross-domain sites.

The default value is none. To configure this header, set the xPermittedCrossDomainPolicies object to one of the following values in string format.

  • none
  • masteronly
  • bycontenttype
  • byftpfilename
  • all

X-XSS-Protection 

The X-XSS-Protection header controls XSS filtering.

The default value is 0. To configure this header, set the xXssProtection object to one of the following boolean values.

  • 0
  • 1

For information about these directives, see MDN Web Docs: X-XSS-Protection.

See Also

Developer Preview Feature

Feature is available as a developer preview. Feature is not generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements. All commands, parameters, and other features are subject to change or deprecation at any time, with or without notice. Do not implement functionality developed with these commands or tools.