Function use_nonce

pub fn use_nonce() -> Option<Nonce>
Expand description

Accesses the nonce that has been generated during the current server response. This can be added to inline <script> and <style> tags for compatibility with a Content Security Policy.

ⓘ
#[component]
pub fn App() -> impl IntoView {
    provide_meta_context;

    view! {
        // use `leptos_meta` to insert a <meta> tag with the CSP
        <Meta
            http_equiv="Content-Security-Policy"
            content=move || {
                // this will insert the CSP with nonce on the server, be empty on client
                use_nonce()
                    .map(|nonce| {
                        format!(
                            "default-src 'self'; script-src 'strict-dynamic' 'nonce-{nonce}' \
                            'wasm-unsafe-eval'; style-src 'nonce-{nonce}';"
                        )
                    })
                    .unwrap_or_default()
            }
        />
        // manually insert nonce during SSR on inline script
        <script nonce=use_nonce()>"console.log('Hello, world!');"</script>
        // leptos_meta <Style/> and <Script/> automatically insert the nonce
        <Style>"body { color: blue; }"</Style>
        <p>"Test"</p>
    }
}