• Skip to main content

Santiago Garza

Software Engineer

  • Blog
  • Photos
  • Contact
  • Tools
    • Text To Image AI

Enhancing AWS Cognito Hosted UI with Cloudflare Workers: A Step-by-Step Guide

August 15, 2024 by Santiago Leave a Comment

AWS Cognito is a powerful tool for managing user authentication and authorization in your applications, with its hosted UI feature making it easy to deploy a secure login page without having to code it yourself. However, the customization options available through the AWS console can be limiting when it comes to making minor styling adjustments or adding custom content. For developers looking to maintain a consistent brand experience without the need to build a custom SSO UI from scratch, Cloudflare Workers provide a flexible and efficient solution.

In this blog post, I’ll guide you through using a Cloudflare Worker to apply advanced customizations to your AWS Cognito hosted UI. By the end, you’ll have a fully customized sign-in page that seamlessly aligns with your brand’s design, all without having to create an entirely new UI.

Why Use Cloudflare Workers for AWS Cognito UI Customization?

AWS Cognito’s hosted UI provides a convenient way to handle user sign-in, sign-up, and password management flows. However, customizing the UI beyond what the AWS console offers can be challenging. For instance, if you want to add specific styles, update the page title, or insert custom HTML elements, you might think you need to develop a custom UI from scratch.

But that’s not the case. Cloudflare Workers, combined with the HTMLRewriter API, allow you to make these customizations seamlessly, enabling you to:

  • Save Development Time: Avoid the complexity of building a custom SSO UI just to make minor styling tweaks.
  • Maintain Brand Consistency: Ensure your Cognito pages align with your overall brand design by applying custom styles and content.
  • Enhance User Experience: Improve the user experience with tailored modifications like custom titles, links, and branding elements.

How It Works

The core of this solution lies in a Cloudflare Worker script that intercepts the HTML response from AWS Cognito and applies the necessary modifications using the HTMLRewriter API.

Cognito Hosted UI customized using only options available in AWS Console
Cognito Hosted UI after deploying the Cloudflare Customization Worker. Notice the descriptive title, favicon, and link after the form.

Try it out

View CUSTOMIZED HOSTED UI

Step 1: Setting Up the Worker

The core of this solution lies in a Cloudflare Worker script that intercepts the HTML response from AWS Cognito and applies the necessary modifications using the HTMLRewriter API.

Follow along by pulling the codebase on the GitHub repository.

The Cloudflare Worker Script

Below is the Cloudflare Worker script that handles the customization. Each section of the script is annotated to explain its purpose:

export default {
    async fetch(request: Request, env: any): Promise<Response> {
        // Fetch the original response from the AWS Cognito hosted UI
        let res = await fetch(request);
        const contentType = res.headers.get("Content-Type") || "";

        // Only process GET requests with HTML content
        if (request.method !== 'GET' || !contentType.startsWith("text/html")) {
            return res;
        }

        try {
            let newRes = new HTMLRewriter()
                .on('head', {
                    element(element) {
                        // Append custom favicon and styles to the head
                        element.append(`<link rel="icon" href="https://www.santiagogarza.co/wp-content/uploads/2020/04/cropped-sg-favicon-1-32x32.png" sizes="32x32">`, { html: true });
                        element.append(`<link rel="icon" href="https://www.santiagogarza.co/wp-content/uploads/2020/04/cropped-sg-favicon-1-192x192.png" sizes="192x192">`, { html: true });
                        element.append(`<style>
                            .submitButton-customizable:active,
                            .submitButton-customizable:focus,
                            .submitButton-customizable:visited {
                                color: #fff;
                                border-color: transparent !important;
                                background-color: #bd0460 !important;
                            }
                            body {
                                background-color: #EAEBED !important;
                            }
                        </style>`, { html: true });
                    }
                })
                .on('title', {
                    element(element) {
                        // Set a custom title for the sign-in page
                        element.setInnerContent(`SSO Sign In - Santiagogarza.co`, { html: true });
                    }
                })
                .on('form', {
                    element(element) {
                        // Add a link below the form to redirect users back to the main site
                        element.after(`<div style="text-align:center;"><a href="https://www.santiagogarza.co/"> ← Go to santiagogarza.co</a></div>`, { html: true });
                    }
                })
                .transform(res);

            return newRes;
        } catch (error) {
            // Log any errors that occur during the transformation
            console.error(error);
            return res;
        }
    }
};

Summary

In this step, you’ve set up a Cloudflare Worker that intercepts and customizes the AWS Cognito hosted UI. The script modifies the HTML to include custom styles, a new page title, and additional content.

Step 2: Configuring the Route in wrangler.toml

For the Worker to intercept and modify the AWS Cognito hosted UI responses, you need to configure the route in your wrangler.toml file. This step ensures that the Worker is applied to the correct subdomain where your Cognito hosted UI is served.

Adding the Route

Add the following configuration to your wrangler.toml making sure to update using your own domain and hosted-ui subdomain:

routes = [
    { pattern = "sso.santiagogarza.co/*", zone_name = "santiagogarza.co"}
]

This configuration routes all traffic for sso.santiagogarza.co through the Cloudflare Worker, allowing it to intercept and modify the UI as needed.

Summary

You’ve now configured the route in wrangler.toml, ensuring that all traffic to your AWS Cognito hosted UI is processed by the Cloudflare Worker.

Step 3: Deploying the Worker

Deploying the Worker is straightforward using Cloudflare’s Wrangler CLI.

Install project dependencies

If you haven’t installed the project dependencies yet, you can do so with:

npm install

Logging in to Cloudflare

Once installed, log in to your Cloudflare account:

npm run deploy

Publishing the Worker

Finally, deploy your Worker with:

wrangler publish

Your customizations should now be live, and your AWS Cognito hosted UI should reflect the styles, titles, and content modifications defined in the Worker script.

Troubleshooting Tips

Here are some common errors you might encounter and how to resolve them:

  • Error 1003: Content type not supported: Ensure that your Worker only processes GET requests with text/html content.
  • Worker not triggering: Double-check your wrangler.toml route configuration to make sure it’s correctly set up for your subdomain.
  • Styling not applied: Verify that the HTMLRewriter API is correctly modifying the elements you want to style.

Conclusion

With Cloudflare Workers, you can significantly enhance the AWS Cognito hosted UI without the need for a full custom UI implementation. This approach not only saves valuable development time but also ensures that your user authentication flows remain consistent with your brand’s look and feel. Whether you’re adding custom styles, updating page titles, or inserting additional content, Cloudflare Workers offer a powerful and flexible solution for making these customizations.

By following the steps outlined in this guide, you can start applying these advanced customizations to your AWS Cognito UI today. To see the full code and explore more details, visit the GitHub repository.

Happy Hacking!

Related

Filed Under: Tech Tips, Tutorials

About Santiago

I am a Professional Software Engineer with over a decade of experience. I have a passion for exploring how different technologies can enhance our everyday lives and enjoy sharing this knowledge with others. Learn more about me, or get in touch through my contact form.

Reader Interactions

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • GitHub
  • WordPress
  • Twitter
  • Instagram
  • LinkedIn

Copyright © 2025 · Santiago Garza

 

Loading Comments...