We use cookies to ensure you get the best experience on our website. Read our privacy policy

Skip to main content
Cloudflare Pages Staging Environment illustration showing preview deployments
Home Blog Cloudflare

How To Create A Secure Staging Environment For Cloudflare Pages

Testing website changes before they go live is essential for maintaining a professional online presence. Learn how to create a secure, password-protected staging environment for your Cloudflare Pages site.

Published on:
Clock Time to complete: 15 minutes
  • Check Circle

    Test new features without affecting live users

  • Check Circle

    Check mobile browser compatibility

  • Check Circle

    Catch bugs and issues before they impact your production site

  • Check Circle

    Allow clients and team members to review changes before approval

  • Check Circle

    Maintain SEO rankings by preventing search engines from indexing test content

Cloudflare Pages makes setting up a staging environment straightforward, but there are important security considerations to address. This guide covers everything you need to create a secure, professional staging setup.

  1. Log in to GitHub and navigate to your repository
  2. Click on the “main” branch dropdown (top left of the repository)
  3. Click “View all branches”
GitHub repository interface showing the branch dropdown with View All Branches option highlighted
  1. Click “New branch”
GitHub interface showing the New Branch creation dialog
  1. Name your branch “staging” and create it from your main branch

This branch will serve as the source for your staging environment. Any changes pushed to this branch will automatically deploy to your staging site.

  1. Log in to your Cloudflare dashboard
  2. Navigate to “Workers & Pages”
Cloudflare dashboard navigation showing Workers & Pages section
  1. Select your Pages project
  2. You should see a new preview deployment (likely failed due to missing environment variables)
  3. Go to “Settings”
  4. Make sure “Preview” is selected in the “Environment” dropdown
  5. Click on the “Edit branch control” button
Cloudflare Pages project settings page with Edit branch control button highlighted
  1. In the branch control editor make sure the production branch is set to “main” or “master”
  2. For preview branch, select “custom branches” and under include type in “staging”
  3. Click save
Cloudflare Pages branch control configuration panel showing production and preview branch settings

For more details on preview environments you can check out the Cloudflare Pages documentation.

Your staging environment needs the same environment variables as production. If you plan to use a different database for staging you will need to add the database credentials as environment variables.

  1. Still in the Settings tab, scroll to “Environment variables”
  2. Click “Add variable”
  3. Make sure to select “Preview” environment when adding variables
  4. Save your changes

If you retry the deployment now, your staging site will be publicly accessible and indexable by search engines. Let’s fix that.

To keep search engines from indexing your staging site we need to add a “noindex” header to the response.

  1. In your Cloudflare dashboard, go to “Rules” > “Overview”
  2. In the dropdown “Show Templates For” select “Transform Reuests or Responses”
  3. Click “create rule” on the template named “Add static header to response”
Cloudflare Rules dashboard showing Transform Requests or Responses templates
  1. Name your rule (e.g., “Add noindex to staging”)
  2. Select “custom filter expression”
  3. Set the following conditions:
    • Field: “URI Full”
    • Operator: “wildcard”
    • Value: http://staging.yourdomain.com/* (your staging domain)
  4. Add another condition with OR operator:
    • Field: “URI Full”
    • Operator: “wildcard”
    • Value: http://staging.yourdomain.pages.dev/*
  5. Under “Then…”, select “Set static” for the action
  6. Header name: “X-Robots-Tag” (Make sure it’s capitalized)
  7. Value: “noindex, nofollow”
  8. Click “Save”
Cloudflare Rules configuration panel for adding noindex headers to staging environment

Limited Time Launch Sale

Check out our AstroJS starter template and get your site up and running in a day.

GET 60% OFF!

Now let’s create a custom subdomain for your staging site:

  1. Go back to your Pages project and click on the “Custom domains” tab and “Add custom domain”
  2. Enter staging.yourdomain.com and click “Continue”
  3. Confirm
Cloudflare Pages custom domain configuration screen for adding staging subdomain
  1. Click “Check DNS records”
Cloudflare Pages DNS records verification screen for custom domain
  1. Go to “DNS” in your Cloudflare dashboard
  2. Verify that you have a CNAME record for your domain
    • Type: “CNAME”
    • Name: “staging”
    • Target: “staging.yourdomain.pages.dev” (your Pages staging domain)

Now retry the deployment and open the staging preview URL. To verify the noindex tag is working:

  1. Open browser developer tools
  2. Go to the Network tab and refresh the page
  3. Click on the main document request
  4. Check that response headers include “X-Robots-Tag: noindex, nofollow”
Browser developer tools network tab showing X-Robots-Tag header in response

For additional security, let’s add password protection. There are two approaches:

  1. In your Cloudflare dashboard, go to “Workers & Pages” Cloudflare Workers & Pages dashboard for creating a new worker
  2. Click “Create a Service” > “Create Worker” and select the “Hello World” option
Cloudflare Worker template selection screen with Hello World option
  1. Click Edit Code
Cloudflare Worker interface with Edit Code button highlighted
  1. Replace the default code with this authentication code, thank you to Max Ivanov for the code
  2. Change the username and password to your desired values
const USERNAME = 'demouser';
const PASSWORD = 'demopassword';
const REALM = 'Secure Area';
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const authorization = request.headers.get('authorization');
if (!request.headers.has('authorization')) {
return getUnauthorizedResponse('Provide User Name and Password to access this page.');
}
const credentials = parseCredentials(authorization);
if (credentials[0] !== USERNAME || credentials[1] !== PASSWORD) {
return getUnauthorizedResponse('The User Name and Password combination you have entered is invalid.');
}
return await fetch(request);
}
function parseCredentials(authorization) {
const parts = authorization.split(' ');
const plainAuth = atob(parts[1]);
const credentials = plainAuth.split(':');
return credentials;
}
function getUnauthorizedResponse(message) {
let response = new Response(message, {
status: 401,
});
response.headers.set('WWW-Authenticate', `Basic realm="${REALM}"`);
return response;
}
  1. Deploy the worker
  2. Go to the worker’s “Settings” tab
  3. Make sure the workers.dev and preview URLs are disabled
  4. Under “Routes”, click “Add route”
Cloudflare Worker settings tab showing Routes configuration section
  1. Set the zone to the current project
  2. Route: “staging.yourdomain.com/*”
  3. Failure mode closed block
  4. Save
Cloudflare Worker route configuration panel for staging domain

The *.pages.dev domain can’t be password-protected via Workers directly. To handle this we will redirect the pages.dev URLs to the custom domain:

  1. Go to “Rules” > “Bulk Redirects”
  2. Click “Add redirects” > “Manually add redirects”
Cloudflare Bulk Redirects interface for manually adding redirects
  1. Add two new redirect URLs
    • redirect 1
      • Source URL: yourdomain.pages.dev/
      • Target URL: https://yourdomain.com/
      • Status code: 301 (Permanent redirect)
      • Check all boxes under “edit parameters” except “Include Subdomains”
    • redirect 2
      • Source URL: staging.yourdomain.pages.dev/
      • Target URL: https://staging.yourdomain.com/
      • Status code: 301 (Permanent redirect)
      • Check all boxes under “edit parameters” except “Include Subdomains”
  2. Save and exit
Cloudflare Bulk Redirects configuration panel for redirecting pages.dev URLs to custom domain

This is outside the scope of this guide, please refer to the Cloudflare Access documentation for more information. I chose to use the workers method because it doesn’t require a payment method to set up.

  1. Push changes to your staging branch in GitHub
  2. Wait for Cloudflare Pages to deploy the changes
  3. Visit staging.yourdomain.com
  4. Enter the username and password when prompted
  5. Verify your changes appear correctly
  6. Check that the noindex header is present

Your staging site is now secure, protected from search engines, and requires authentication to access.

  • Check Circle

    Always test changes in staging before merging to main

  • Check Circle

    Create a pull request workflow that requires staging approval

  • Check Circle

    Consider automating visual regression tests between staging and production

  • Check Circle

    Document the staging URL and credentials for your team

With this setup, you can confidently test changes, gather feedback, and maintain a professional production environment without worrying about unfinished work being visible to the public.

Related Articles

Read more Cloudflare articles
North Star Themes Logo

Subscribe to our newsletter

Get the latest AstroJS tips and tricks right to your inbox

Email: [email protected]

© 2025 North Star Themes

Web Kit Provided By North Star Themes