javascripthugodocsy

Lunr.js with offline search is not working


I am trying to enable Lunr.js offline search in my hugo site with docsy theme.

I have enabled the following in my config.toml file

# Enable Lunr.js offline search
offlineSearch = true
offlineSearchSummaryLength = 70
offlineSearchMaxResults = 10

and disabled the following algolia_docsearch , gcs_engine_id

when I run locally on my mac, the search functionality works.

however, when I deployed it on S3 backed by CloudFront, it gives me the following error

Refused to load the script 'https://unpkg.com/lunr@2.3.8/lunr.min.js' because it violates the following Content Security Policy directive: "script-src 'self' https://code.jquery.com https://stackpath.bootstrapcdn.com https://cdnjs.cloudflare.com". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Upon some trial and test, I have realized that this CDN 'https://unpkg.com/lunr@2.3.8/lunr.min.js causes an issue.

When I add the following CDN, it works!.

<script src="https://cdnjs.cloudflare.com/ajax/libs/lunr.js/2.3.9/lunr.min.js" integrity="sha512-4xUl/d6D6THrAnXAwGajXkoWaeMNwEKK4iNfq5DotEbLPAfk6FSxSP3ydNxqDgCw1c/0Z1Jg6L8h2j+++9BZmg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

My hugo project use the following this submodules https://github.com/google/docsy/tree/2bedb2ff278eddba4a7fc4441ca6bf7a42caeb68

This submodules by default put "https://unpkg.com/lunr@2.3.8/lunr.min.js" and does not allow me to change it to "https://cdnjs.cloudflare.com/ajax/libs/lunr.js/2.3.9/lunr.min.js"

My question is how could I resolve this Content Security Policy issue to enable "offline-search"

The submodules overwrites my changes. So it prevents me to put any content security meta tag. https://github.com/google/docsy/tree/2bedb2ff278eddba4a7fc4441ca6bf7a42caeb68


Solution

  • If you want your search to be available offline when running locally, you cannot rely on third-party servers on the internet.

    Even your solution based on Cloudflare will stop working at some point when the file is no longer available on your local cache.

    The safest option is to download the files you need, store them in /static/js/ (so they are really available offline) and update the URLs so they point to the local files.