Skip to content

How to pass env variables into contentSecurityPolicyΒ #627

@kalnode

Description

@kalnode

I'm trying to pass env variables into contentSecurityPolicy. I understand there's challenges in doing this directly in nuxt.config.ts, and have read suggestions (link, link) that a Nitro server plugin could modify CSP per-route and may be able to achieve this. However, I'm unable to get this to work; looking for suggestions.

Ultimately I'm striving for:

  1. Configure everything through env variable (such that no hard URLs are in the codebase)
  2. Centralize all config (e.g. in nuxt.config.ts), however I'd live with a nitro plugin, so as long as # 1 is satisfied.

STARTING POINT

nuxt.config.ts

// Works, but need the URL to come from env variables
export default defineNuxtConfig({
    security: {
            headers: {
                contentSecurityPolicy: {                
                    // DESIRED, BUT FAILS - Ideally, we pass env value
                    'img-src': ["'self'", 'data:', process.env.SOMEURL] 
                    
                    // WORKS, BUT NOT IDEAL
                    'img-src': ["'self'", 'data:', 'https://some.website.net']
                }
            }
    }
}

TRYING NITROPLUGIN INSTEAD

Based on discussions, it's been suggested to use a custom NitroPlugin and hooks to modify CSP elsewhere, and perhaps in this way be able to pass env variables. Below I'm trying out this snippet: https://nuxt-security.vercel.app/advanced/hooks#available-hooks. The plugin works (can change CSP per-route), however I'm still unable to pass env variables.

Is there something additional needed?

server/myplugin/myplugin.ts

export default defineNitroPlugin((nitroApp) => {
    nitroApp.hooks.hook('nuxt-security:routeRules', async (appSecurityOptions) => {
        appSecurityOptions['/**'] = defuReplaceArray(
            {
                headers: {
                    contentSecurityPolicy: {                        

                        // Fails - getting undefined/null on these gets
                        //"img-src": ["'self'", 'data:', process.env.IMAGEBASEURL ]
                        //"img-src": ["'self'", 'data:', useRuntimeConfig().public.IMAGEBASEURL ]
                        
                        // Works, however still need to make this URL come from env variables
                        "img-src": ["'self'", 'data:', 'https://some.website.net' ]
                    }
                }
            },
            appSecurityOptions['/**']
        )
    })
})

Am I going in the wrong direction, or has there been new developments since the past discussions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions