Visual annotations for links

Following on from my post on link annotation, a thought about visual indicators for links to external sites – eg:

As an aside: this “external link” thing is not a new idea – see the Revised EXTERNAL LINK proposal from 2018 – which is a rehash of rejected proposals from 2006 & 2012.

Back on track… my preference is that no links should force a new Navigable Context (a new tab or window) as that detracts from the usability of the site by certain people. I can (and should) semantically indicate the link is to an external site, however I’d like to also visually indicate the link is to an external site (without adding verbal content to the page which is a detraction for non-visual users) – thus allowing the user to choose whether to start a new context for that page.

The annotation rel="external" is the obvious way to semantically indicate the external link – that comes from the previous discussion… however how about the visual indicator?

The visual indicator is fairly easy – even without an available UniCode character: I create a css variable that is a graphic, which I can then append to the link element:

:root {
  --icon-external-link: url('data:image/svg+xml,\
	<svg role="img" xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 20 20"> \
		<g style="stroke:rgb(35,82,124);stroke-width:1"> \
        <line x1="5" y1="10" x2="5" y2="19" /> \
        <line x1="14" y1="14" x2="14" y2="19" /> \
        <line x1="5" y1="19" x2="14" y2="19" /> \
        <line x1="5" y1="10" x2="9" y2="10"  /> \
        <line x1="10" y1="7" x2="17" y2="7"  /> \
        <line x1="17" y1="7" x2="17" y2="14" /> \
        <line x1="10" y1="14" x2="17" y2="7" style="stroke-width:1.5" /> \
		</g> \
	</svg>');
}

a.show_icon::after {
  content: "";
  background: no-repeat var(--icon-external-link);
  padding-right: 1em;
}

This is fine, works well – but requires you to add class="show_icon" to all the links.

I realised that we can use the rel="external" we’ve already applied to the link, saving the whole “remember to add a class” thing:

a[rel="external"]::after {
  content: "";
  background: no-repeat var(--icon-external-link);
  padding-right: 1em;
}

Obvious, in retrospect

Why div is not the Devils Work

When I started getting more serious about web accessibility, my “go-to” tool for checking semantic structure and usability was the accessibility tree in firefox – it would generate a structure like this:

(From craigslist)

All those unlabelled generics have no semantic meaning, and how can you find your way around the page? Terrible!!

Of course, we can’t add aria labelling to div, and I learnt about articles and sections, and how the div was bad. Quoting the HTML standard at whatwg,org:

Authors are strongly encouraged to view the div element as an element of last resort, for when no other element is suitable. Use of more appropriate elements instead of the div element leads to better accessibility for readers and easier maintainability for authors.

… so I switched to articles & sections (and, along the way, discovered that a section is a landmark only if it has an accessible label)

This leads to a slightly better:

(from the Noteable service)

However, I’ve recently realised that this is pretty rubbish when using an actual screen-reader… as you end up with the screen-reader fankled in knots, and saying something along the lines of

[out of list] [out of region] [out of region] [out of region] [“Brief description for BioChemistry Notebook and link to full descriptions”, (cursor)article region]

If you look at this using something like the ARIA DevTools plugin, so see an rendition like:

(same noteable page)

… and you realise that actually the regions you’ve labelled (because that’s what’s shown in dev-tools) are actually making life harder for listeners.

Be switching back to divs you can actually reduce the semantic structure to:

(modified noteable page)

which then reads the same part as

[out of list] [out of region] [out of region] [“Brief description for BioChemistry Notebook and link to full descriptions”, (cursor)article region]

After this, one needs to have discussions with the service people as to whether things like visual “cards” on a page are semantically discrete components, or just a visual artifact.

Thoughts on link annotation

Hyperlinks, specifically Anchor elements

From the html specification: “A hyperlink can have one or more hyperlink annotations that modify the processing semantics of that hyperlink.”

The important part of that statement is processing semantics : these annotations are there to provide additional guidance to programs that consume the page, not humans using the Mark 1 eyeball

The spec defines this in 4.6.8 Link types – and for this discussion, I’m only looking at <a ...> elements.

These annotations are given in the rel attribute, and are a space-separated list of terms.

Traversables

Before we start on these annotations and what they mean, we need to understand a concept in the HTML spec documentation: “Traversables”

As you browse the web, you collect a whole bunch of documents and referenced data – creating a trail of history and vaguely linked documents, which you can Navigate through. When you open a new browser window, or a new tab in an existing browser, you create a new (blank) navigable.

A Traversable navigable is the currently active set of history et al data…. essentially, the currently active tab – for us visually-oriented people

The importance of this becomes apparent when creating anchor links with target attributes.

  • If you do <a href="foo">foo</a>, this simple replaces the current page with the new page…. and adds to the current Traversable navigable. Lets call this the “same context”
  • If you do <a href="foo" target="_blank">foo</a>, this leaves the current page alone and opens the page in a new window/tab – it creates a new Traversable navigable stack (there’s no “history” to go back to the calling page). Lets call this a “new context”
  • If you do <a href="foo" target="somename">foo</a>, this leaves the current page alone and opens the page in the window/tab named “somename” (creating a new window/tab if it doesn’t exist) – If the Traversable navigable stack already exists, it adds the page to it: “history” will step back through the various pages that have been loaded into that “somename context”

The last two variations can be annotated: if the target is _blank (ie, always create a new window/tab), then use rel="opener"; if the target is a (possibly existing) named target (eg, target is somename), then use rel="noopener"

Relationships or Authority

In this arena, I’m referring to how this page indicates any relationship/authority to the document in the given link

External pages

You can use rel="external" to indicate that the document is not part of the current site – eg

<a href="https://example.com/foo/" rel="external">foo</a>
<a href="https://MySite.com/foo/">foo too</a>

Both URLs are absolute, so the only way to actually tell one is for an external document is the annotation

Pages we do not endorse

There are times when we link to a page, however we also want to indicate we don’t necessarily agree/endorse it’s content

Consider search page that both indexes internal documents, but also has a dataset of solutions harvested from external sources… and all results created dynamically, as internal pages: in this situation, we may want to indicate we do not necessarily trust/endorse the results we harvested (and imply we endorse/trust our own data).

rel="nofollow" is your friend here: nofollow indicates the original author/publisher does not endorse the referenced document

Referrers

As you browses the web, there is an optional HTTP “Referer” header – which sites can use for a number of reasons. By adding a rel="noreferrer" annotation, you can specifically request the client not to include the optional header (if it was going to)

Example

<a href="https://one.example.com/foo/"
rel="external nofollow noreferrer noopener"
target="example">foo</a>
<a href="https://one.example.com/bah/"
rel="external nofollow noreferrer noopener"
target="example">bah</a>
<a href="https://two.example.com/baz/"
rel="external nofollow noreferrer noopener"
target="example">baz</a>

This creates three links to three different pages. Each one is to a external site, whose content we do not endorse, nor do we want our webpage added in the referer header (trying to reduce tracking.) We also indicate that the pages are all going to open in the same, but not our, “context”

Less obvious, but sometimes helpful annotations

There are a few additional annotations that can be used:

alternate: links to the current document in alternate version – eg, An Accessibility Statement may have a link to download a pdf copy of that statement

<a href="foo" rel="alternate">
Download this document as a PDF
</a>

These three all apply to the current page – which may, or may not, apply to whatever service the web pages are describing. For example, the “terms of service” for a cloud mail provider are probably different to the “terms of service” to the web pages about that service.

  • license : The link is for the copyright licence for the current page
  • privacy-policy : The link is for the usage/privacy policy that applies to the current page
  • terms-of-service : The link is for the terms of service that apply to the current page
<a href="foo" rel="privacy-policy">
Website Privacy Policy
</a>

prev / next : These two imply the page is part of a series, and link to the pages either side
bookmark : This is related to prev / next, and give a permalink to the parent:

<a href="foo" rel="prev">← Goto previous page</a>
<a href="https://shortener.example.com/1k2jeb"
rel="bookmark">Table of Contents</a>
<a href="bah" rel="next">Goto next page →</a>

search : Search the current document and related pages. This is probably not the same as search the whole site – consider a document on health and safety policies on a corporate website:

<a href="hns_search" rel="search">
Search the Health and Safety documentation
</a>

is now semantically indicated to be limited to a subset of the whole site.

author : You may want to indicate who the page author is, amongst a list of names

<a href="mailto:j.bloggs@example.com" rel="author">
Email Jo Bloggs
</a>
<a href="mailto:A.Mouse@example.com">
Email Anonni Mouse
</a>

Tricks for labelling landmarks

The basic structure

I have a suite of “cards” that look something like this:

<section class="docs_card">
<header>
<img src="/images/exemplars/foo/arrays.png"
alt="taken from the arrays notebook" />
</header>
<div class="docs_card_body">
<h5 class="heading-paragraph">Python arrays</h5>
<p>Introducing python arrays.</p>
</div>
<footer class="card-footer">
<p><a
href="https://example.com/some/path/arrays.ipynb">
View Notebook
</a></p>
</footer>
</section>

This gives us consistency of display, and by using flex/grid layouts we have something that is properly responsive across multiple screen sizes.

Table of contents / jump to any card

First things first: we want to be able to jump to any card – for that, we can simply add an id to the outer section element:

<section class="docs_card" id="foo_a_arrays_nb">

Then your Table Of Contents can have

<a href="#foo_a_arrays_nb">Python arrays</a>

which links down to the `id`.

Jump destinations that “identify” themselves

I have seen pages where jump-to points “identify” themselves when you hover over them – I prefer the MDN style to the W3c Working Group style

<h2 id="some-id">
<a class="show-hash" href="some-id">
My heading
</a>
</h2>

… and then the CSS has:

.heading-anchor::before {
content: "#";
margin-left: -.8em;
padding-right: .8em;
}
anchor:not(:hover, :focus)::before {
visibility: hidden;
}

…. YMMV

Improving accessibility

The first problem is we’re going to get a complaint that we have multiple “View Notebook” links all going to different places – this viloates WCAG 2.4.9 (Link Purpose Only)

The second problem is that none of our sectional data are actually semantically meaningful – in effect, they are just div elements with fancy names

Fixing the links

There are two options here, and they’re probably 99.99% identical:

<a href="https://example.com/some/path/arrays.ipynb"
aria-label="View Notebook: Arrays">View Notebook</a>

vs….

<a href="https://example.com/some/path/arrays.ipynb">
View <span class="sr_only">Arrays</span> Notebook</a>

    There are some nuanced differences/challenges though

    Distinction via aria labels

    This seems a fairly easy solution, however needs some care: WCAG 2.5.3 says the Accessible Name should contain the visible name. Best Practice is that the visible test should be at the start of the Accessible Name… hence the label would always be “: something” appended to the “View Notebooks” text.

    It could also, with some clever work, be templateable – so something that could be created from an external data-source

    This solution is somewhat frowned upon, given “First Rule of ARIA: Don’t Use ARIA”

    Distinction via hidden text

    Hiding text via CSS is a well know, and very common, trick. It adds a bit more typing, and maybe slightly harder for the developer to read.

    It provides a much better versatility, there’s no WCAG 2.5.3 Best Practice to trip us up, as the hidden text appear wherever we want – however it’s also not something that could easily be templated

    Adding simple labels to define semantic structure

    The following should be fairly obvious:

    <section class="docs_card"
    id="foo_a_arrays_nb"
    aria-labelledby="foo_a_arrays_nb_h5">
    <header aria-label="Image from notebook">
    <img src="/images/exemplars/foo/arrays.png"
    alt="taken from the arrays notebook" />
    </header>
    <div class="docs_card_body">
    <h5 class="heading-paragraph" id="foo_a_arrays_nb_h5">
    Python arrays
    </h5>
    <p>Introducing python arrays.</p>
    </div>
    <footer class="card-footer"
    aria-label="link to notebook">
    <p><a
    href="https://example.com/some/path/arrays.ipynb">
    View Notebook
    </a></p>
    </footer>
    </section>

    We now, semantically, have a containing section, with a header and a footer…. and the stuff between.
    The containing section gets its accessible name from the heading in the body of the card, and the header & footer are given simple names.

    This is not good practice: there are now multiple locations which cannot be “programmatically distinguished”…. and we could do better

    Unique labels for those headers and footers

    We can, certainly, create aria-label entries for each element…. but that’s going to be hard work, and repeat a lot of text – so here’s a neater solution:

    <!-- somewhere in the page, doesn't matter where, we create some text to reference -->
    <p aria-hidden="true" id="_hid1">Contains graphic for</p>
    <p aria-hidden="true" id="_hid2">Contains link to</p>
    <p aria-hidden="true" id="_hid3">notebook</p>
    <!-- Now in our sets of cards.... -->
    <section class="docs_card"
    id="foo_a_arrays_nb"
    aria-labelledby="foo_a_arrays_nb_h5">
    <header
    aria-labelledby="_hid1 foo_a_arrays_nb_h5 _hid3">
    <img src="/images/exemplars/foo/arrays.png"
    alt="taken from the arrays notebook" />
    </header>
    <div class="docs_card_body">
    <h5 class="heading-paragraph" id="foo_a_arrays_nb_h5">
    Python arrays
    </h5>
    <p>Introducing python arrays.</p>
    </div>
    <footer class="card-footer"
    aria-labelledby="_hid2 foo_a_arrays_nb_h5 _hid3">
    <p><a
    href="https://example.com/some/path/arrays.ipynb">
    View Notebook
    </a></p>
    </footer>
    </section>

    This will create a header label of Contains graphic for Python arrays notebook and a footer label of Contains link to Python arrays notebook

    Fun and games – the <aside> element

    The aside element has been giving me some challenges for a while now: I was sure I was using it right, however some of my automated validator testers were flagging it up as a failure.

    Here’s the simplified code:

    <main>
      <div class="container">
        <section aria-label="various options">
          <p>Blah blah</p>
          <form>
            <label>Select a thing
              <select id="a">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
                <option value="4">Option 4</option>
              </select>
            </label>
            <button id="ab" onClick="do_magic()"
                    type="submit">
          <form>
        </section>
        <section
          id="notes_section"
          aria-label="Brief notes on your option"
          aria-live="polite"
          aria-atomic="true">
          <p>more waffle</p>
          <aside aria-label"more info...">For fuller
             details, see the <a 
             href="some_link">full details</a> 
             page</aside> 
        </section>
      </div>
    </main>
    

    The page renders fine, and is correct as I read the WebSpec aside page, however I get an “Aside should not be contained in another landmark” error…. in some, but not all, validators.

    It took me a while, but I eventually figured it out – this code passes:

    <main>
      <div class="container">
        <section aria-label="various options">
          <p>Blah blah</p>
          <form>
            <label>Select a thing
              <select id="a">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
                <option value="4">Option 4</option>
              </select>
            </label>
            <button id="ab" onClick="do_magic()"
                    type="submit">
          <form>
        </section>
        <article
          id="notes_section"
          aria-label="Brief notes on your option"
          aria-live="polite"
          aria-atomic="true">
          <p>more waffle</p>
          <aside aria-label"more info...">For fuller
             details, see the <a 
             href="some_link">full details</a> 
             page</aside>
        </article>
      </div>
    </main>
    

    The difference? section become article….. and what’s more annoying is that, in the service, the content of the id="notes_section" location is dependent on the current option in select input, so it’s not really a separate article.

    No, I can’t figure it out either…..

    Adding light/dark to a website

    [Edited January 2026 to use the light-dark() function and an improved switching system]

    These are my notes on how I did it. Most of what I have done is not new, and has been pulled in from various places, most notably from various videos that Kevin Powell posted.

    Starting point

    The starting point is to have all your colours defined as variables, in one place in your css. Ideally, do this at root level, so they exist before anything is rendered:

    :root {
      --text-primary: #333333;
      --text-secondary: #ffffff;
      --primary: #a50034;
      --bg-secondary: #fff0e8;
      --bg-primary: #ffffff;
      --default-link: #0066ff
    

    Following “System Preferences”

    The first, and really easy, fix is just to get the website to follow whatever light/dark theme the computer is set to – aka “System Preferences”.

    This requires two things:

    1) set the document to recognise light and dark modes – two methods available:

    • either in the css:
        html {
          color-scheme: light dark;
        }
    
    • or the head of the document:
        <meta name="color-scheme" content="light dark" />
    

    2) Provide the dark-mode colours in the css. The light-dark() css function became “Baseline” in 2024, meaning it’s available in all [sane] browsers:

    :root {
      --text-primary: light-dark(#333333, #cccccc);
      --text-secondary: light-dark(#ffffff, #000000);
      --primary: light-dark(#a50034, #5affcb);
      --bg-secondary: light-dark(#fff0e8, #000f17);
      --bg-primary: light-dark(#ffffff, #000000);
      --default-link: light-dark(#0066ff, #ff8800);
    }
    

    That’s it….. when a user changes their computer to use a dark-mode or a light-mode “skin”, the web page will follow.

    Minor gotcha: variables that are not colours

    We use CSS variables for may things: sizes used repeatedly; display modes, or even inline svg graphics – for example:

    :root {
      --logo_displaymode_light: inline-block;
      --logo_displaymode_dark: none;
    
      // colour to match --default-link value, but as rgb
      --icon-external-link: url('data:image/svg+xml,\
    	<svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 20 20"> \
          <title>External link indicator</title>
          <g style="stroke:rgb(0, 102, 204);stroke-width:1"> \
            <line x1="5" y1="10" x2="5" y2="19" /> \
            <line x1="14" y1="14" x2="14" y2="19" /> \
            <line x1="5" y1="19" x2="14" y2="19" /> \
            <line x1="5" y1="10" x2="9" y2="10"  /> \
            <line x1="10" y1="7" x2="17" y2="7"  /> \
            <line x1="17" y1="7" x2="17" y2="14" /> \
            <line x1="10" y1="14" x2="17" y2="7" style="stroke-width:1.5" /> \
    	  </g> \
    	</svg>');
    }
    

    To switch these, you do need to include a media selector:

    @media (prefers-color-scheme: dark) {
      :root {
        --logo_displaymode_light: none;
        --logo_displaymode_dark: inline-block;
    
        // colour to match --default-link value, but as rgb
        --icon-external-link: url('data:image/svg+xml,\
        <svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 20 20"> \
          <title>External link indicator</title> \
          <g style="stroke:rgb(255, 136, 0);stroke-width:1"> \
            <line x1="5" y1="10" x2="5" y2="19" /> \
            <line x1="14" y1="14" x2="14" y2="19" /> \
            <line x1="5" y1="19" x2="14" y2="19" /> \
            <line x1="5" y1="10" x2="9" y2="10"  /> \
            <line x1="10" y1="7" x2="17" y2="7"  /> \
            <line x1="17" y1="7" x2="17" y2="14" /> \
            <line x1="10" y1="14" x2="17" y2="7" style="stroke-width:1.5" /> \
          </g> \
        </svg>');
      }
    }
    

    Allow users to select a mode…. and remember it.

    This bit is more convoluted…. and needs three parts:

    • Define the color-scheme on the root (html) element
    • We use localstorage to remember what theme we want,
    • then use javascript to redefine the color-scheme value in the style on the root element as needed

    We put all the javascript in the head section, so it gets run before the page fully renders – we need to do this to avoid the “Persistent White Flash” as the page loads

    <script>
      const themeStore = "noteableThemeStore";
      const themeSelectorId = "theme";
    
      const getColorScheme = () => {
        // cascading options:
        //  - Localstore content
        //  -  or existing root color-scheme style
        //  - or specifically 'light dark'
        return (
          localStorage.getItem(themeStore) ||
          document.documentElement.style.colorScheme ||
          "light dark"
        );
      };
    
      const updateColorScheme = (scheme) => {
        localStorage.setItem(themeStore, scheme);
        document.documentElement.style.colorScheme = scheme;
      };
    
      const currentColorScheme = getColorScheme();
    
      updateColorScheme(currentColorScheme);
    
      // Update select
      document.getElementById("theme").value = currentColorScheme;
    </script>
    

    Note that the default, when there’s no localStorage value, is to “follow system preferences”

    As the page load, the script executes. It:

    1. Gets the currently defined scheme (from localstore, else from the current DOM, else specifically "light dark"
    2. It sets the value in localstore and modifies the style of the html element
    3. [tries to] set the value of theme selector element …. if there is one

    Allowing the user to select a theme

    This is all well-and-good – but how do we choose this localstorage item? We use an HTML select with an onChange event:

    The html is nice and easy:

         <label>Theme:
          <select
            name="themepicker"
            id="theme"
            onChange="updateColorScheme(this.value);"
          >
            <option value="light dark">System</option>
            <option value="light">Light</option>
            <option value="dark">Dark</option>
          </select>
        </label>
    

    (note the value matches what we store in localstore and the string we set the style to – this is important)

    So, when the user selects, say “Dark”, the browser calls updateColorScheme(dark), which:

    1. Sets localstore to dark
    2. updates the root element to contain a hard-coded style:
      <html ..... style="color-scheme: dark;">

    Auto-closing disclosures

    Disclosures are, in web-land, fragments of page that can be hidden / shown. The native HTML form for this is the “details” and “summary“ elements, and has recently been expanded with the inclusion of the “popover” API

    There are two problems with the raw details/summary solution:

    1. Each disclosure is independent, meaning you can have as many open / closed as you like
    2. As each disclosure changes state, the page is re-flowed as the visible content changes.

    If you consider the image below – the details part is the black text with the arrow-head to the left, and the summary part is everything in the redish box (that’s all styled with css – natively it’s just inherited colours & backgrounds). By opening the “Starting a Notebook Server” disclosure, all the text below that is pushed down the page… some of which will disappear below the visible view-port

    Likewise, when closing the “Starting a Notebook Server” disclosure, all the text below that is pulled back up the page.

    Auto-closing disclosures

    One of the things that many people want to do is to auto-close one item when another is opened – and this is available natively!

    You can group details together into groups using the name attribute, and only one item from a group can be visible – see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details#multiple_named_disclosure_boxes for information.

    Of course, when the page is re-flowed, the view-port does not move with the content, so auto-closing a (fairly lengthy) disclosure that is above the view-port may result in the newly opened disclosure also being re-drawn above the view-port.

    This is not solvable with by html itself – it is, afterall, a pagination issue

    Retaining disclosure visibility

    The solution I have for this is a small fragment of javascript:

    document.addEventListener("DOMContentLoaded", () => {
      const allDetails = document.querySelectorAll("details");
    
      allDetails.forEach((detail) => {
        detail.addEventListener("toggle", (event) => {
          if (detail.open) {
            allDetails.forEach((otherDetail) => {
              var target = detail.id;
              location.href = "#" + target;
            });
          }
        });
      });
    });
    

    This requires each details element to have a unique id, however we can then effectively “jump” to that (flagged as open) element.

    Creating disclosures using templates

    For my application, I actually create these disclosures using a data-source and a template

    Sample data (as a yaml file)

    sections:
      - code: fa
        questions:
          - question: "'Notebook' seems to mean many things, why?"
            code: 1
            answer: The term is a generic one, and can either apply to 'Notebook App', 'Notebook Dashboard', or 'Notebook document'. See <a href="#faq_hi_2">What is a computational notebook</a> below.
          - question: Which programming languages are supported on Noteable?
            code: 2
            answer: <p>Noteable currently supports Python 3 and R. We have experience with notebooks using Haskell, Julia, and Stata kernels. Talk to us about other languages.</p>
          - question: Can I share notebook documents/files with other users?
            code: a
            answer: |
              <p>Notebook servers have <samp>git</samp> tools installed. See <a href="#faq_fa_3">How can I use Git in Noteable?</a> for details.</p>
              <p>You can download and upload files using the Download and Upload functions in the Jupyter classic, JupyterLab and RStudio interfaces.</p>
    
    

    relevant html fragment (actually part of an njk template)

        {% for section in faq.sections %}
          {% for question in section.questions %}
              <details id="{{ section.code }}_{{ question.code }}" name="nbguide_disclosure_item" class="faq_question" aria-labelledby="faq_{{ section.code }}_{{ question.code }}">
                <summary id="faq_{{ section.code }}_{{ question.code }}">{{ question.question  | safe }}</summary>
                {{ question.answer | safe }}
              </details>
          {% endfor %}
        {% endfor %}
    
    

    playwright and testing multiple environments

    Following on from my post on configuring Cypress to be able to test multiple environments, here’s how I did the same thing in playwright (the node version)

    As before, my “Use Case” is I have some number of defined environments in Kubernetes Clusters ( live, qa, dev), plus some number of personal developer environments…. and I don’t want those personal configs getting put into the repo (developers may want to use personal login details, for example)

    The solution that worked for me is essentially the same as the Cypress idea: there are multiple config files, and some environment variable is used. In this case, I’m “hacking” the idea of .env to my benefit.

    The whole idea of dotenv is that there’s an external file that loads a bunch of values into process.env for us … and note that dotenv can specify the path to the file being loaded. As with the Cypress example, we use an environment variable to select the one we want to use.

    The “magic” happens in the central playwright.config.ts file:

    //playwrite.config.ts
    import { defineConfig, devices } from '@playwright/test';
    import * as dotenv from 'dotenv';
    
    // import the right config - default to beta, change using a `CONTEXT` env variable
    let context:string;
    
    if (process.env.CONTEXT == null) {
      context = 'beta'
    } else {
      context = process.env.CONTEXT;  
    }
    dotenv.config({ path: `myConfigs/env-${context}` });
    
    export default defineConfig({
      .....
    });
    

    … and we place the various config files in, you guessed it, a directory called myConfigs – and name each file env-foo

    base_url=https://example.com
    something=something_else
    ad=nausium
    

    In the tests, we then have something akin to:

    import { test, expect } from '@playwright/test';
    
    const baseUrl = process.env.base_url ?? "https://example.com";
    const something = process.env.something ?? "";
    
    test.describe('Test something', () => {
        ....
    });
    

    To select the appropriate config file, run:

    CONTEXT=live npx playwright test
    

    where the value of CONTEXT matches the identifier of the config file.

    Cypress 10 and testing multiple environments

    Cypress is a tool for doing [end-to-end] testing of web services.

    One of the facets of web services is you often have multiple environments: the actual “live” service, a Beta/QA instance, and maybe some specialist variants… and it would be good to be able to apply the tests to any of these environments.

    Before Cypress 10, configuration was through a file called cypress.json… and there is plenty of documentation on the internet to create cypress/config/foo.json files to modify the configuration for each environment.

    With Cypress 10, this changed – and the cypress.json file was changed to cypress.config.js (or cypress.config.ts, if you’re going that route) – and the cypress/config/foo.json solutions don’t work.

    My “Use Case” is I have some number of defined environments in Kubernetes Clusters (live, qa, dev), plus some number of personal developer environments…. and I don’t want those personal configs getting put into the repo (developers may want to use personal login details, for example)

    I found one solution for cypress 10 [https://dev.to/samelawrence/how-to-test-in-multiple-environments-in-cypress-10-1i9h], where they put the multiple config elements into setupNodeEvents in cypress.config – however that doesn’t work for my case: no personal developer config in files in the repo.

    This is my solution – there may be better, but this works for me:

    // cypress.config.ts
    import { defineConfig } from 'cypress';
    import * as fs from 'fs';
    
    function getConfigurationByFile(file) {
      const pathToConfigFile = 'cypress/config/' + file + '.json';
      return JSON.parse(fs.readFileSync(pathToConfigFile, 'utf-8'));
    }
    
    export default defineConfig({
      e2e: {
        baseUrl: 'https://beta.example.com', // no trailing slash
        specPattern: 'cypress/e2e/*.{spec.ts,cy.js}',
        env: {
          login_username: '<username>',
          login_password: '<password>',
          something: 'interesting',
        },
        // various other config items
    
        setupNodeEvents(on, config) {
          if (config.env.context) {
            const localData = getConfigurationByFile(config.env.context);
            if (localData.baseUrl) {
              config.baseUrl = localData.baseUrl;
            }
            if (localData.env) {
              config.env = localData.env;
            }
          }
    
          // IMPORTANT return the updated config object
          return config;
        },
      },
    });
    

    (The code looks a bit weird, because I use the eslinter, and it requires imports, not requires – YMMV)

    This sets up a default configuration, with some env variables…. and the setupNodeEvents routine looks for an env field of context, and if it exists, modifies the config from it.

    // cypress/config/live.json
    {
      "baseUrl": "https://example.com",
      "env": {
        "login_username": "fred",
        "login_password": "flintstone",
      }
    }
    

    The update the config function, in this example, is pretty crude – it only changes baseUrl & env, and simply replaces a with b – it makes no attempt to merge lists or dicts in any way… so, in this example, something is lost from the env variables.

    To select the appropriate config-file, run:

    npx cypress run --env context=live

    …. where the value of the context variable matches the name of the json file.

    Authentication vs Authorisation

    The two are often combined into a single action… logging in… but are actually very different:

    Consider an aeroplane flight – that requires both Authentication and Authorisation.

    When you line up to board a plane, they check both your passport and your boarding-pass/ticket.

    • The Passport “Authenticates” who you are, but says nothing about your place on the plane
    • The boarding-pass “Authorises” a place on the plane, but says nothing about who you are

    The boarding crew check your passport [Authentication] and boarding pass [Authorisation], and possibly cross-check with a list of recognised names.

    If either are wrong – perhaps a boarding pass for a later flight, or the ticket was booked in someone else’s name – you are not permitted onto the plane.