
Web applications load different resources to display their content and provide functionality. These resources include JavaScript files, CSS stylesheets, images, fonts, videos and third-party scripts.
However, allowing a browser to load scripts and other resources from unrestricted sources can create security risks. If an attacker manages to inject malicious JavaScript into a website, the browser may execute it within the website's context. This can lead to attacks such as Cross-Site Scripting (XSS).
Content Security Policy (CSP) is a browser security mechanism that helps reduce these risks. It allows website owners to define which sources are permitted to provide particular types of content.
CSP is especially useful for websites that use third-party scripts, dynamic content, external libraries and user-generated information.
This article explains Content Security Policy, its directives, HTTP headers, implementation methods, XSS protection, reporting, common mistakes and real-world applications.
Content Security Policy is a browser security standard that allows a website to control where resources can be loaded from and which content is permitted to execute.
A website communicates its policy to the browser through an HTTP response header or a CSP meta element in HTML.
For example, a website can configure its policy to:
Allow JavaScript only from its own origin.
Load images from its own domain and selected image services.
Restrict stylesheet sources.
Prevent the execution of inline scripts.
Block plugins and embedded objects.
Restrict where forms can be submitted.
Control which websites can frame its pages.
When the browser receives the policy, it checks resource requests and execution attempts against the configured rules.
If a resource violates the policy, the browser can block it and, depending on the configuration, report the violation.
Without an appropriate content security policy, a website may allow scripts and resources from sources that it does not actually need.
For example, imagine an application that accepts comments from users. If the application contains an XSS vulnerability, an attacker might inject JavaScript into a comment.
A restrictive CSP can prevent that injected script from executing when it does not have the required authorisation.
CSP is a defence-in-depth security control. It does not replace secure coding, input validation, output encoding or proper authentication.
CSP works through rules called directives. Each directive controls a particular category of resources or browser behaviour.
A server sends a CSP header with its HTTP response.
Example:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'
The browser interprets these instructions and applies them when loading or executing resources.
This policy means:
default-src 'self': Use the website's own origin as the default permitted source for resource categories covered by this fallback.
script-src 'self': Load scripts from the same origin.
object-src 'none': Block object-based embedded content.
base-uri 'self': Restrict the URLs that can be used in the HTML base element.
If a page attempts to load a script from an unauthorised external domain, the browser blocks that resource.
A user requests a web page.
The server returns HTML and HTTP response headers.
The browser reads the CSP policy.
The browser identifies resources required by the page.
It checks each resource against the applicable directive.
Permitted resources are processed.
Violating resources are blocked or reported according to the policy.
The policy is enforced by the browser, not by the application server inspecting every JavaScript execution itself.
CSP provides several directives for controlling resource loading and browser behaviour.
The default-src directive acts as a fallback for several resource-loading directives when they are not explicitly configured.
Example:
Content-Security-Policy: default-src 'self'
This restricts covered resources to the website's own origin unless a more specific directive overrides the fallback.
It does not automatically replace every CSP directive. For example, base-uri, form-action and frame-ancestors have separate behaviour.
The script-src directive controls permitted JavaScript sources.
Example:
Content-Security-Policy: script-src 'self'
This allows scripts from the website's own origin.
It can also support nonces and cryptographic hashes to authorise specific scripts.
A restrictive script policy is particularly important for reducing the impact of XSS vulnerabilities.
The style-src directive controls where stylesheets and certain style resources can come from.
Example:
Content-Security-Policy: style-src 'self'
This permits stylesheets from the website's own origin.
Inline styles may require additional policy decisions, such as hashes, nonces or carefully selected exceptions.
The img-src directive controls permitted image sources.
Example:
Content-Security-Policy: img-src 'self' https://images.example.com
This allows images from the same origin and a selected image host.
The connect-src directive controls connection destinations used by browser interfaces such as:
Fetch API
XMLHttpRequest
WebSocket
EventSource
Beacon API
Example:
Content-Security-Policy: connect-src 'self' https://api.example.com
This is useful for restricting the destinations to which frontend code can connect.
The font-src directive controls font resources.
Content-Security-Policy: font-src 'self' https://fonts.example.com
The frame-src directive controls the sources from which a page can load nested browsing contexts such as iframes.
Content-Security-Policy: frame-src https://video.example.com
The frame-ancestors directive controls which websites are allowed to embed the current page inside frames.
Content-Security-Policy: frame-ancestors 'self'
It is useful for reducing clickjacking risks.
Unlike many resource directives, frame-ancestors does not fall back to default-src and cannot be configured through a CSP meta element.
The object-src directive controls resources loaded through elements such as object and embed.
Content-Security-Policy: object-src 'none'
Many modern applications do not need these elements, so blocking them can reduce unnecessary exposure.
The base-uri directive restricts which URLs can be used in an HTML base element.
Content-Security-Policy: base-uri 'self'
This helps prevent attackers from changing how relative URLs are resolved through an injected base element.
The form-action directive controls the destinations to which forms can submit data.
Content-Security-Policy: form-action 'self'
It does not use default-src as a fallback.
This directive instructs browsers to treat eligible insecure resource requests as upgraded to secure requests.
Content-Security-Policy: upgrade-insecure-requests
It can help with legacy content migration, but it does not replace fixing insecure URLs in the application itself.
CSP directives use source expressions to identify permitted resources.
Allows resources from the same origin as the document.
script-src 'self'
Blocks all sources covered by the directive.
object-src 'none'
A website can allow a particular origin.
img-src https://images.example.com
Wildcard patterns can permit multiple matching subdomains or hosts.
They should be used carefully because broad source permissions can weaken the policy.
A nonce is a random value generated for a particular response. The server adds it to an authorised script element and includes the same value in the CSP header.
Example HTML:
<script nonce="random-response-value">
console.log("Authorised script");
</script>
Example policy:
Content-Security-Policy: script-src 'nonce-random-response-value'
The example value is illustrative. Production applications must generate unpredictable, sufficiently strong nonces for each response and must not reuse them across unrelated responses.
A CSP hash allows a specific inline script or style block based on its cryptographic content.
For example, a policy may authorise a script using a SHA-256 hash.
If the script content changes, the hash must also change.
Hashes are useful for static content, while nonces are often convenient for server-rendered pages that generate dynamic HTML.
Cross-Site Scripting is a vulnerability in which attackers cause a website to execute malicious scripts in a user's browser.
XSS commonly occurs when an application handles untrusted input without appropriate output encoding or safe rendering.
CSP can help reduce the impact of these vulnerabilities by restricting script execution.
A strict script policy can block scripts from unauthorised sources.
For example:
Content-Security-Policy: script-src 'self'; object-src 'none'; base-uri 'self'
If an attacker injects a script that is not authorised by the policy, the browser may block its execution.
A stronger approach can use nonce-based script authorisation and avoid unsafe inline JavaScript.
However, CSP is not a complete XSS solution. Attackers may still exploit application vulnerabilities if the policy is too permissive, incorrectly configured or bypassable through trusted script behaviour.
Developers should combine CSP with:
Context-aware output encoding.
Safe DOM manipulation.
Input validation.
Secure templating.
Appropriate sanitisation for permitted HTML.
Secure session handling.
Regular security testing.
CSP supports different modes depending on whether a policy is enforced or used for monitoring.
The Content-Security-Policy header activates an enforced policy.
Example:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'
The browser blocks resources that violate the policy.
This mode is suitable for production after the policy has been tested.
The Content-Security-Policy-Report-Only header allows developers to observe policy violations without blocking the resources.
Example:
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; object-src 'none'
This is useful when introducing CSP to an existing application.
Developers can identify legitimate external resources, inline scripts and other dependencies that would be blocked by enforcement.
Report-only mode does not provide actual resource blocking.
A practical rollout can follow these stages:
Identify existing resource dependencies.
Create an initial policy.
Enable report-only mode.
Review browser violations and server reports.
Adjust legitimate source permissions.
Remove unnecessary inline scripts and unsafe dependencies.
Enable enforcement.
Monitor the policy continuously.
CSP can be configured through server response headers or an HTML meta element.
HTTP response headers are generally preferred because they support the complete policy functionality and can be applied consistently across responses.
The following example uses Express to send a basic CSP header.
const express = require("express");
const app = express();
app.use((req, res, next) => {
res.setHeader(
"Content-Security-Policy",
[
"default-src 'self'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data:",
"font-src 'self'",
"connect-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"frame-ancestors 'self'",
"form-action 'self'"
].join("; ")
);
next();
});
app.get("/", (req, res) => {
res.send("<h1>Secure Application</h1>");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
This example provides a starting policy. Real applications may need additional sources for APIs, images, fonts or other resources.
The policy should be based on actual application requirements rather than copied without testing.
Helmet is a middleware package that helps configure security-related HTTP headers in Express applications.
Install it:
npm install helmet
Configure it:
const express = require("express");
const helmet = require("helmet");
const app = express();
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
frameAncestors: ["'self'"],
formAction: ["'self'"]
}
}
})
);
app.listen(3000);
Helmet helps simplify header configuration, but developers must still understand the policy and verify that it matches their application's requirements.
For applications that need inline scripts, a nonce-based policy can provide a more controlled approach.
A simplified Express example:
const express = require("express");
const crypto = require("crypto");
const app = express();
app.get("/", (req, res) => {
const nonce = crypto.randomBytes(16).toString("base64");
res.setHeader(
"Content-Security-Policy",
`default-src 'self'; script-src 'self' 'nonce-${nonce}'; object-src 'none'; base-uri 'self'`
);
res.type("html").send(`
<!DOCTYPE html>
<html>
<head>
<title>CSP Nonce Example</title>
</head>
<body>
<h1>Secure Page</h1>
<script nonce="${nonce}">
console.log("Authorised script executed");
</script>
</body>
</html>
`);
});
app.listen(3000);
The server generates a new random nonce for every response and uses it in both the CSP header and the authorised script element.
In production, ensure that dynamically generated HTML, caching and templating preserve the correct per-response nonce relationship.
Monitoring is important because a restrictive policy may block resources that an application genuinely needs.
For example, a website may depend on a payment service, analytics script or external font provider.
If those resources are not included in the policy, the browser may block them.
Modern CSP supports reporting through the report-to directive, which uses the Reporting API and a separately configured Reporting-Endpoints response header.
Example:
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"
Content-Security-Policy: default-src 'self'; report-to csp-endpoint
The server must implement the corresponding reporting endpoint and process incoming reports safely.
The older report-uri directive is deprecated but may still be encountered in existing applications.
Important information includes:
Blocked resource URLs.
Violated CSP directives.
Affected page locations.
Repeated violation patterns.
Unexpected inline script attempts.
External resources that are no longer required.
Reports should be treated as untrusted input. Avoid storing sensitive data unnecessarily and protect reporting endpoints from abuse.
Adding 'unsafe-inline' to script-src allows inline JavaScript and weakens an important CSP protection.
Where possible, replace inline scripts with external files, nonces or hashes.
Using broad source permissions may allow resources from domains that the application does not actually trust.
Allow only required sources.
Enforcing an untested policy can break application functionality.
Begin with monitoring, investigate violations and introduce enforcement gradually.
Applications may load scripts, images, fonts or API resources from external providers.
Every required resource category should be reviewed before enforcing a restrictive policy.
Reusing a nonce across responses weakens the intended security design.
Generate unpredictable values for individual responses.
CSP cannot correct insecure backend logic, weak authentication, poor authorisation or every form of XSS.
It should be part of a broader application-security strategy.
Developers sometimes configure script restrictions but overlook frame-ancestors and form-action.
These directives address different browser security concerns and should be considered separately.
A carefully configured policy can block unauthorised script execution and reduce the impact of certain XSS attacks.
Websites can specify which origins are allowed to provide scripts, stylesheets, images, fonts and other resources.
The frame-ancestors directive can restrict which websites are allowed to embed a page.
CSP reporting helps developers identify unexpected resource-loading behaviour and possible injection attempts.
Organisations can establish consistent content-loading rules across multiple applications.
A strict policy encourages developers to avoid unnecessary inline scripts and review third-party dependencies.
CSP is powerful, but it has limitations.
Incorrect policies can break legitimate website functionality.
Existing applications may require significant changes to support strict script restrictions.
Third-party integrations can make policy maintenance difficult.
Broad source allowlists can reduce effectiveness.
Browser support and reporting behaviour can vary.
CSP does not prevent all types of malicious content or application vulnerabilities.
Security reports may contain noise and require careful analysis.
Organisations should test policies across their supported browsers and application environments.
Online shopping applications can use CSP to restrict scripts, images and other resources to approved sources.
This is particularly important when payment providers and third-party integrations are involved.
Financial platforms can use restrictive content policies to reduce exposure to injected scripts and control external resource loading.
Software platforms can apply CSP to customer dashboards, administrative panels and account-management interfaces.
CMS platforms often handle user-generated content and third-party extensions. CSP can add another layer of browser-side protection.
Online learning applications can restrict scripts and embedded resources to approved origins while supporting required learning tools.
Internal portals can use CSP to standardise security rules across employee-facing applications.
Create a website with different scripts and resource sources.
Experiment with CSP directives and observe which resources are allowed or blocked.
Build a login interface and configure CSP to restrict JavaScript, stylesheets, images and form destinations.
Test the policy using browser developer tools.
Create a backend endpoint that receives CSP reports and displays common violations.
Include filtering by directive, page and resource source.
Build a server-rendered application that generates a unique nonce for each page response.
Verify that authorised scripts execute while unauthorised inline scripts are blocked.
Create a tool that reads a website's CSP header and identifies potentially weak settings, missing directives and broad source permissions.
Present recommendations without claiming that automated checks can prove a website is secure.
HTML and JavaScript: Understand script execution, DOM manipulation, inline scripts and external resources.
HTTP fundamentals: Learn response headers, status codes, request processing and browser communication.
Web security: Study XSS, clickjacking, injection vulnerabilities and secure application development.
Backend development: Learn how to configure response headers using Node.js, Express or other backend frameworks.
Browser developer tools: Practise inspecting network requests, console errors and CSP violations.
Security testing: Learn how to test policies in report-only and enforcement modes.
Authentication and session management: Understand how browser-based applications handle user identity and access.
Third-party integrations: Learn how analytics, payment providers, fonts and external scripts affect security policies.
Content Security Policy is a useful web-security skill for several technical roles.
Application security engineers identify web vulnerabilities, review security controls and help developers build safer applications.
Web security specialists work on browser security, HTTP headers, XSS prevention and application-hardening practices.
Frontend developers use CSP knowledge to build interfaces that follow secure resource-loading and script-execution practices.
Backend developers configure security headers, server responses and application middleware.
Security testers evaluate web applications for vulnerabilities and verify whether security policies are correctly implemented.
DevSecOps engineers integrate security checks and configuration standards into software delivery workflows.
CSP is one component of the broader knowledge expected in these roles.
Follow this learning path:
Understand HTML, CSS and JavaScript.
Learn how HTTP requests and responses work.
Study common XSS vulnerabilities.
Understand CSP headers and source expressions.
Practise the main CSP directives.
Configure CSP in a Node.js application.
Experiment with nonce-based script authorisation.
Use report-only mode to identify policy violations.
Test enforced policies using browser developer tools.
Build a small secure application and document its policy decisions.
Start with a simple application and gradually introduce stricter rules.
Developers interested in web security and application development can explore:
Online Courses – Explore technology and programming learning resources.
Course Search – Find relevant software-development and security courses.
Web Development – Explore web-development concepts and related skills.
Content Security Policy is an important browser security mechanism that helps website owners control which resources can be loaded and executed. By configuring directives for scripts, stylesheets, images, connections and embedded content, developers can reduce exposure to certain browser-based attacks.
A strong CSP requires careful planning, testing and continuous monitoring. Nonces, hashes, restrictive source rules and violation reporting can help organisations introduce policies without unnecessarily breaking application functionality.
For frontend developers, backend engineers and security professionals, understanding CSP is a valuable step towards building safer web applications.
Content Security Policy is a browser security mechanism that allows a website to specify which sources are permitted to provide scripts, stylesheets, images and other resources.
Its main purpose is to reduce certain browser-based security risks, particularly the impact of Cross-Site Scripting, by restricting resource loading and script execution.
CSP is generally implemented through the Content-Security-Policy HTTP response header. A limited version can also be configured through an HTML meta element.
Content-Security-Policy enforces the policy by blocking violating resources. Content-Security-Policy-Report-Only monitors violations without blocking those resources.
The default-src directive provides a fallback source policy for several resource-loading directives when more specific directives are not configured.
script-src controls which sources are allowed to provide JavaScript and which script execution mechanisms are permitted.
A nonce is an unpredictable value generated for a particular response. It allows the browser to identify specific inline scripts that the server has authorised.
A nonce authorises a script using a random value supplied by the server. A hash authorises content based on its cryptographic hash. Nonces are often useful for dynamic server-rendered pages, while hashes can be useful for stable script content.
No. CSP can reduce the impact of certain XSS attacks, but it cannot guarantee complete protection. Secure output encoding, input handling and safe application design remain necessary.
It instructs the browser not to load resources through elements such as object and embed.
It specifies which websites are allowed to embed a page inside frames. It is useful for reducing clickjacking risks.
frame-src controls which sources the current page can load inside frames. frame-ancestors controls which websites can embed the current page.
Yes. React applications can use CSP through server response headers. Depending on the build setup, they may require nonce configuration for dynamically generated scripts or styles.
Yes. Node.js applications can configure CSP through HTTP response headers or middleware packages such as Helmet.
In enforced mode, the browser blocks the violating resource or action when the policy requires it. Depending on the reporting configuration, it may also generate a violation report.
CSP usually has a small direct performance impact. However, incorrectly configured policies may block required resources and cause application functionality to fail.
It is a CSP directive that instructs browsers to upgrade eligible insecure resource requests to secure requests. It does not replace proper HTTPS configuration.
Yes. Developers can restrict script-src to approved origins, nonces or hashes. Scripts from unauthorised sources will be blocked under an enforced policy.
CSP is supported by modern major browsers, although support for particular directives and reporting features can vary. Applications should test their policies in their supported browser environments.
Start by identifying resource dependencies and testing a policy using report-only mode. Review violations, remove unnecessary dependencies, refine the policy and then enable enforcement gradually.
More News Click here
Discover thousands of colleges and courses, enhance skills with online courses and internships, explore career alternatives, and stay updated with the latest educational news..
Gain high-quality, filtered student leads, prominent homepage ads, top search ranking, and a separate website. Let us actively enhance your brand awareness.