Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Content-Security-Policy

Next.js Security Settings: CSP, SVG Restrictions, and Secure Image Handling

By Freedom251 Team · · 9 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest Next.js setup combines a deliberately narrow Content-Security-Policy (CSP), exact image-source allowlists, conservative SVG handling, and browser-hardening headers. Configure a static CSP in next.config.js when your script sources are known; use a per-request nonce only when legitimate inline scripts require it. Replace broad image host rules with remotePatterns and localPatterns, keep SVG optimization disabled unless you have a specific need, and cap the image optimizer’s source-response size.

These controls protect different boundaries. CSP limits what a page can execute or load, image patterns limit what the server-side optimizer will fetch, and SVG settings prevent active document content from being treated like a harmless bitmap.

As an Amazon Associate I earn from qualifying purchases.

What to configure first

Apply the controls in this order:

  1. Deliver a CSP. Start with a static response header if every script, style, image, font, frame, and connection origin is predictable.
  2. Allow images by exact pattern. Match protocol, hostname, port, pathname, and—when present—the complete query string.
  3. Keep SVG conservative. Do not enable SVG optimization merely to make a file load.
  4. Add browser-hardening headers. Use HSTS, frame protection, MIME sniffing protection, a permissions policy, and a deliberate referrer policy.
  5. Limit optimizer responses. Reduce the default source-image response limit when your application’s assets are smaller.

Testing must cover both the browser and the server-side image optimizer. A page can satisfy CSP and still reject an image because its URL does not match an image pattern; conversely, an image can pass the pattern check but be blocked by the browser’s img-src directive.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set a Content-Security-Policy in Next.js

Use a static policy for predictable applications

Next.js supports CSP through the headers function in next.config.js. A static policy is easier to cache and audit because the same header is sent for every matching route. It works well when scripts and other resources come from a known, finite set of origins.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

The following is a starting point, not a universal drop-in. Enumerate every legitimate origin before deploying, then remove directives or sources your application does not need.

const csp = [
  `default-src 'self'`,
  `script-src 'self'`,
  `style-src 'self' 'unsafe-inline'`,
  `img-src 'self' https://images.example.com data: blob:`,
  `font-src 'self'`,
  `object-src 'none'`,
  `base-uri 'self'`,
  `frame-ancestors 'none'`,
].join('; ')

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.example.com',
        port: '',
        pathname: '/account123/**',
        search: '',
      },
    ],
    localPatterns: [{ pathname: '/assets/images/**', search: '' }],
    dangerouslyAllowSVG: false,
    contentDispositionType: 'attachment',
    contentSecurityPolicy: `default-src 'self'; script-src 'none'; sandbox;`,
    maximumResponseBody: 5_000_000,
  },
  async headers() {
    return [{
      source: '/(.*)',
      headers: [
        { key: 'Content-Security-Policy', value: csp },
        { key: 'X-Content-Type-Options', value: 'nosniff' },
        { key: 'Referrer-Policy', value: 'origin-when-cross-origin' },
      ],
    }]
  },
}

default-src 'self' establishes a same-origin baseline. script-src 'self' limits executable scripts, while object-src 'none' removes a legacy plug-in execution path. base-uri 'self' prevents an injected base element from rewriting relative URLs. frame-ancestors 'none' disallows embedding; change it if a trusted parent site must frame the application. The sample allows inline styles, but 'unsafe-inline' should remain only when the framework or application genuinely requires it.

Use a nonce when inline scripts are genuinely required

A random nonce must be generated for each request in middleware, placed in that response’s CSP, and attached to every authorized inline script. This is different from putting one fixed nonce in next.config.js; a fixed value does not provide meaningful authorization. A nonce policy is appropriate when a static script-src allowlist cannot describe legitimate inline execution. Treat the middleware policy as part of the request lifecycle and verify that all framework-generated or application-generated inline scripts receive the nonce. If you can remove the inline code, a static policy is simpler and easier to reason about.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose directives from actual resource use

Inventory scripts, styles, images, fonts, frames, and network connections before tightening the policy. Add only the origins required by those resources. In particular, img-src should include the origins from which the browser ultimately displays images. For optimized next/image output, the browser commonly receives a same-origin optimizer URL; for deliberately unoptimized remote images, the remote origin also needs to be allowed. CSP does not replace the server-side image allowlist.

Add browser-hardening response headers

Next.js’s headers API documents several complementary controls. Their values must reflect your deployment and embedding requirements.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
Header Security role Decision to make
Strict-Transport-Security Instructs browsers to use HTTPS for the host. Set a duration and subdomain behavior only when every covered host is permanently HTTPS-capable.
Content-Security-Policy Restricts executable code, framing, and resource origins. Use a static policy or a per-request nonce policy based on whether inline scripts are required.
frame-ancestors in CSP Controls which sites may embed the page. Use 'none' when embedding is never required; list trusted parents when it is.
X-Frame-Options Legacy clickjacking protection. Keep it compatible with your embedding model; CSP frame-ancestors is the modern successor.
Permissions-Policy Restricts browser features such as camera, microphone, or geolocation. Disable features the application does not use and scope any required feature to trusted origins.
X-Content-Type-Options: nosniff Stops MIME-type guessing by browsers. Send it on application and asset responses where possible.
Referrer-Policy Controls URL information sent in the Referer header. Choose a policy such as origin-when-cross-origin after considering analytics and privacy needs.

Allow remote images without broad trust

Prefer remotePatterns over domains

images.remotePatterns matches five parts of an image URL: protocol, hostname, port, pathname, and, when specified, the complete search string. Matching is exact and case-sensitive. A mismatch in any component causes the image request to be rejected.

This precision is the security boundary for the server-side optimizer. Use HTTPS, a specific hostname, and the narrowest path that fits the application. If a storage service contains multiple tenants or unrelated files, allow one tenant prefix rather than the entire host.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Pattern field Example Effect
protocol https Rejects an HTTP URL even when the hostname is identical.
hostname images.example.com Limits fetching to that host.
port Empty string Uses the standard port for the selected protocol in the example.
pathname /account123/** Allows only the account’s path subtree.
search Empty string Requires no query string; a URL with query parameters will not match.

Do not migrate new code to images.domains. Next.js has deprecated that option since version 14 because it cannot restrict protocol, port, pathname, or wildcard scope. Replace each broad domain entry with one or more narrowly defined remote patterns.

Understand query-string behavior

When search is specified, the complete query string must match. This matters for signed URLs: a pattern that includes one exact signature will not accept a different signature or an added parameter. If your application intentionally supports varying signed parameters, design the pattern and URL flow accordingly rather than opening an entire host. Never assume that a matching hostname alone protects a shared image service.

Account for the optimizer boundary

The optimizer fetches the remote source on the server, then serves an optimized response to the browser. A remote pattern therefore limits what your server will retrieve, while CSP limits what the browser may render or execute. Keep both controls aligned, and review redirects from the approved host so an apparently narrow rule does not become an unintended fetch path.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Restrict local assets with localPatterns

images.localPatterns applies the same least-privilege idea to local paths. The example /assets/images/** keeps the optimizer focused on an asset subtree instead of every path in the application.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Specify search: '' when query parameters are not part of the asset contract. Omitting search allows all query parameters, which broadens the URLs the optimizer will process. If cache-busting or transformation parameters are required, document the accepted form and test that the resulting URLs match exactly.

Treat SVG as active content

Why SVG needs a separate decision

Next.js notes that SVG has many of the same features as HTML and CSS, which can create vulnerabilities without suitable CSP headers. An SVG is therefore not equivalent to a passive JPEG or PNG: it can contain elements and references that deserve document-level scrutiny.

The conservative default is to avoid optimizing SVG. If the source is known to be SVG and optimization is unnecessary, use unoptimized on that image. This keeps the format-specific handling explicit instead of enabling a global exception.

If dangerouslyAllowSVG is unavoidable

Keep dangerouslyAllowSVG false unless SVG optimization is a deliberate requirement. When it must be true, pair it with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
  • contentDispositionType: 'attachment', so a direct visit downloads the file instead of rendering it in the browser.
  • contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", which blocks scripts and places the delivered SVG in a sandboxed context.

Next.js documents attachment as the default content-disposition behavior because it forces direct image URLs to download. Preserve that behavior for SVG unless you have reviewed the consequences of inline rendering and have compensating controls.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Limit image response size and direct access

The documented Next.js 15 image reference lists a 50 MB default source-response limit for the optimizer. That is a ceiling, not a target. If your application expects smaller assets, reduce maximumResponseBody; the sample uses 5_000_000 bytes. A lower limit reduces exposure to unexpectedly large downloads and makes failures easier to diagnose.

Set limits based on real asset requirements. A limit that is too low will reject legitimate uploads; one that is too high increases the work a remote fetch can impose. Monitor rejected responses and adjust the contract rather than silently widening the limit.

Implementation procedure

  1. Inventory origins. List every script, style, image, font, frame, and connection origin used by production pages. Separate resources that are browser-loaded from images fetched server-side by the optimizer.
  2. Write the baseline CSP. Start with default-src 'self', restrictive script-src, object-src 'none', base-uri 'self', and an explicit img-src. Add only required sources.
  3. Choose delivery. Put the policy in headers() when it is static. Generate a per-request nonce in middleware only for legitimate inline-script authorization.
  4. Define remote patterns. Set HTTPS explicitly, name the exact host, constrain the pathname, and decide whether a query string is allowed. Test URLs with different ports, casing, paths, and parameters.
  5. Define local patterns. Limit optimized local images to the required directory and specify the query-string rule deliberately.
  6. Lock down SVG. Leave dangerouslyAllowSVG disabled and mark known SVG sources unoptimized. If enabling it, configure attachment disposition and the sandbox CSP together.
  7. Set hardening headers. Add HSTS only for an HTTPS-ready deployment, use nosniff, choose a referrer policy, restrict browser features with Permissions-Policy, and configure frame protection for your embedding needs.
  8. Reduce the response limit. Set maximumResponseBody below the 50 MB default when your asset contract permits.
  9. Test negative cases. Confirm that an unapproved host, protocol, port, path, query string, and oversized response fail, while every approved production URL succeeds.

Troubleshoot next/image rejection

Protocol or hostname mismatch

Compare the requested URL with the pattern character by character. An http URL will not match an https pattern, and a subdomain is not interchangeable with its parent hostname.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Port mismatch

Development URLs often include a nonstandard port. If the pattern specifies a port, it must match exactly; if production uses the standard port, maintain separate environment-appropriate patterns rather than allowing every port.

Path mismatch

Check the complete pathname, including a leading slash and account or bucket prefix. A pattern for /account123/** does not authorize an image under another prefix.

Unexpected query parameters

Inspect the final URL, not the URL copied from an application record. When search is an empty string, any query parameter causes rejection. When search is omitted in a local pattern, all query parameters are allowed, which may be broader than intended.

Case mismatch

Matching is case-sensitive. Differences in hostname or path casing can produce a rejection even when the URL appears visually equivalent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

SVG-specific failure

If an SVG is rejected or behaves unexpectedly, first remove the need for optimization by using unoptimized. If policy requires dangerouslyAllowSVG, verify both the attachment disposition and the sandboxed image CSP; enabling only one is incomplete.

Browser CSP violation after the server accepts the image

Open the browser’s CSP report and identify the blocked destination. Add only the legitimate origin or directive required by that resource. Remember that server-side remote-pattern approval does not grant browser permission, and browser CSP approval does not authorize the optimizer to fetch an unallowlisted source.

Production review checklist

  • The CSP is sent on every intended route and contains no unused wildcard sources.
  • Nonce values, if used, are generated per request and attached to every authorized inline script.
  • Remote patterns specify the narrowest practical protocol, host, path, and query behavior.
  • Local patterns do not accidentally allow arbitrary query parameters.
  • images.domains is absent from new configuration.
  • SVG optimization remains disabled unless its sandbox and attachment controls are present.
  • The optimizer’s response limit reflects the largest legitimate source image, not the 50 MB default by habit.
  • HSTS, frame protection, Permissions-Policy, nosniff, and Referrer-Policy values match the deployment’s HTTPS and embedding requirements.
  • Automated tests cover rejected protocols, hosts, ports, paths, query strings, casing, SVG behavior, CSP violations, and oversized responses.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Content-Security-PolicyCSPNext.jsnext/imagesecure image handlingSVG securityWeb Security

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.