Adding Password Protection to 11ty Pages Using PageCrypt
When building static sites with Eleventy (11ty), you might occasionally need to password-protect certain pages. While static sites don't have built-in authentication mechanisms, we can implement client-side encryption using PageCrypt, a lightweight JavaScript solution that encrypts HTML content and requires a password to decrypt it.
The Implementation
Here's how to add password protection to specific pages in your 11ty site:
eleventyConfig.addTransform("secure", async function(content, outputPath) {
const theContent = content;
if(this.page.inputPath.includes("/secure/")) {
// Write it to a file or send as an HTTPS response.
const encryptedHTML = await encryptHTML(content, 'password')
return encryptedHTML;
}
return theContent;
});
This code uses 11ty's transform feature to encrypt pages during the build process. The transform looks for pages in a "secure" directory and encrypts them using PageCrypt's encryption function.
How It Works
- The transform runs on all pages during build time
- It checks if the page's input path contains "/secure/"
- If it does, the content is encrypted using PageCrypt
- The encrypted HTML is returned instead of the original content
Directory Structure Convention
One limitation of 11ty transforms is that they don't have access to front matter context. This means we can't use front matter to mark pages for encryption. Instead, this implementation uses a directory-based approach: any pages inside a "secure" directory will be encrypted.
For example:
src/
secure/
private-page.md # Will be encrypted
secret-stuff.md # Will be encrypted
public-page.md # Won't be encrypted
Using PageCrypt
PageCrypt is a client-side solution that encrypts HTML content. The encryption process uses the Web Crypto API to implement AES-256-GCM encryption with PBKDF2 key derivation.
When users try to access an encrypted page, they'll be prompted for a password. The decryption happens entirely in the browser using JavaScript.
Considerations
- This is client-side encryption, so the encrypted content is still downloaded to the user's browser
- The password is hardcoded in the transform (you might want to use environment variables instead)
- All pages in the "secure" directory will use the same password
- The encryption adds some overhead to your build process
Conclusion
While not as robust as server-side authentication, this solution provides a simple way to add basic password protection to static pages in your 11ty site. It's particularly useful for personal sites or internal documentation where you need basic access control without setting up a full authentication system.
Remember to handle your passwords securely and consider whether client-side encryption meets your security requirements.
Link to PageCrypt GitHub repository
Try it
I've set up a page for you to see how it works. Click the button below. The password is simply password
.