Here’s Ashley Rich at Delicious Brains writing about all the layers of caching that are relevant to a WordPress site. I think we all know that caching is complicated, but jeez, it’s a journey to understand all the caches at work here. The point of cache being speed and reducing burden on the worst bottlenecks and slowest/busiest parts of a web stack.
Here’s my own understanding:
Files can be cached by the browser. This is the fastest possible cache as no network request happens at all. Assets like images, CSS, and JavaScript are often cached this way because they don’t change terribly frequently, but you have to make sure you’re telling browsers that it’s OK to do this and have a mechanism in place to break that cache if you need to (e.g. by changing file names). You very rarely cache the HTML this way, as it changes the most and file-name-cache-busting of HTML seems more tricky than it’s worth.
Files can be cached at the CDN level. This is great because even though network traffic is happening, CDN servers are very fast and likely geographically closer to users than your origin server. If users get files from here, they never even trouble your origin server. You’ll need a way to break this cache as well, which again is probably through changing file names. You might cache HTML at this level even without changing file names if you have a mechanism to clear that cache globally when content changes.
The origin server might cache built HTML pages. On a WordPress site, the pages are built with PHP which probably triggers MySQL queries. If the server can save the result of the things that have already executed, that means it can serve a “static” file as a response, which it can do much faster than having to run the PHP and MySQL. That’ll work for logged out users, who all get the same response, but not for logged in users who have dynamic content on the page (like the WordPress admin bar).
The database has its own special caching. After a MySQL query is executed, the results can be saved in an Object Cache, meaning the same request can come from that cache instead of having to run the query again. You get that automatically to some degree, but ideally it gets wired up to a more persistent store, which you do not get automatically
Phew. It gets a little easier with Jamstack since your pages are prebuilt and CDN-hosted already, and in the case of Netlify, you don’t even have to worry about cache busting.
But even as complex as this is, I don’t worry about it all that much. This WordPress site uses Flywheel for hosting which deals with the database and server-level caching, I have Cloudflare in front of it with special WordPress optimization for the CDN caching, and roll-my-own file-name cache busting (I wish this part was easier). I’d certainly trust SpinupWP to get it right too, given Ashley’s great writeup I’m linking to here.
Authentication and access control are required for most applications, but they often distract us from building core features. In this article, I’ll cover a straightforward way to add auth and access control in React.
Instead of adding a static library that you have to keep up to date or re-research each time you build a project, we’ll use a service that stays up to date automatically and is a much simpler alternative to Auth0, Okta, and others.
React authentication
There are two main things your React application needs to do to sign on a user:
Get an access token from an authentication server
Send the access token to your backend server with each subsequent request
These steps are the same for pretty much all authentication, whether that’s standard email and password, magic links, or single sign on (SSO) providers like Google, Azure, or Facebook.
Ultimately, we want our React app to send an initial request to an authentication server and have that server generate an access token we can use.
JWT access tokens
There are different choices for what type of access token to use, and JSON Web Tokens (JWTs) are a great option. JWTs are compact, URL-safe tokens that your React application can use for authentication and access control.
Each JWT has a JSON object as its “payload” and is signed such that your backend server can verify that the payload is authentic. An example JWT looks like:
It’s important to note that this payload is readable by anyone with the JWT, including your React application or a third party. Anyone that has the JWT can read its contents.
However, only the authentication server can generate valid JWTs. Your React application, your backend server, or a malicious third party cannot generate valid JWTs, only read and verify them.
When your backend server receives a request with a JWT, it should verify the JWT as authentic by checking it against the public key for that JWT. This allows your application server to verify incoming JWTs and reject any tokens that were not created by the authentication server (or that have expired).
The flow for using a JWT in your React application looks like this:
Your React app requests a JWT from the authentication server whenever the user wants to sign on.
The authentication server generates a JWT using a private key and then sends the JWT back to your React app.
Your React app stores this JWT and sends it to your backend server whenever your user needs to make a request.
Your backend server verifies the JWT using a public key and then reads the payload to determine which user is making the request.
Each of these steps is simple to write down, but each step has its own pitfalls when you actually want to implement it and keep it secure. Especially over time, as new threat vectors emerge and new platforms need to be patched or supported, the security overhead can add up quickly.
Userfront removes auth complexity in React apps
Userfront is a framework that abstracts away auth complexity. This makes it much easier for you to work with authentication in a React application and, perhaps most importantly, it keeps all the auth protocols updated for you automatically over time.
The underlying philosophy with Userfront is that world-class auth should not take effort – it should be easy to set up, and security updates should happen for you automatically. Userfront has all the bells and whistles of authentication, Single Sign On (SSO), access control, and multi-tenancy, with a production-ready free tier up to 10,000 monthly active users.
For most modern React applications, it’s a great solution.
Setting up authentication in React
Now we’ll go through building all the main aspects of authentication in a React application. The final code for this example is available here.
Set up your React application and get your build pipeline in order however you prefer. In this tutorial, we’ll use Create React App, which does a lot of the setup work for us, and we’ll also add React Router for client-side routing. Start by installing Create React App and React Router:
Now the home page has your signup form. Try signing up a user:
Your signup form is in “Test mode” by default, which will create user records in a test environment you can view separately in your Userfront dashboard:
Continue by adding your login and password reset forms in the same way that you added your signup form:
At this point, your signup, login, and password reset should all be functional.
Your users can sign up, log in, and reset their password.
Access control in React
Usually, we don’t want users to be able to view the dashboard unless they are logged in. This is known as a protected route.
Whenever a user is not logged in but tries to visit /dashboard, we can redirect them to the login screen.
We can accomplish this by updating the Dashboard component in src/App.js to handle the conditional logic.
When a user is logged in with Userfront, they will have an access token available as Userfront.accessToken(). We can check for this token to determine if the user is logged in. If the user is logged in, we can show the dashboard page, and if the user is not logged in, we can redirect to the login page.
Add the Redirect component to the import statement for React Router, and then update the Dashboard component to redirect if no access token is present.
// src/App.js
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
Redirect, // Be sure to add this import
} from "react-router-dom";
// ...
function Dashboard() {
function renderFn({ location }) {
// If the user is not logged in, redirect to login
if (!Userfront.accessToken()) {
return (
<Redirect
to={{
pathname: "/login",
state: { from: location },
}}
/>
);
}
// If the user is logged in, show the dashboard
const userData = JSON.stringify(Userfront.user, null, 2);
return (
<div>
<h2>Dashboard</h2>
<pre>{userData}</pre>
<button onClick={Userfront.logout}>Logout</button>
</div>
);
}
return <Route render={renderFn} />;
}
Notice also that we’ve added a logout button by calling Userfront.logout() directly:
Now, when a user is logged in, they can view the dashboard. If the user is not logged in, they will be redirected to the login page.
React authentication with an API
You’ll probably want to retrieve user-specific information from your backend. In order to protect your API endpoints, your backend server should check that incoming JWTs are valid.
There are many libraries available to read and verify JWTs across various languages; here are a few popular libraries for handling JWTs:
While the user is logged in, their access token is available in your React application as Userfront.accessToken().
Your React application can send this as a Bearer token inside the Authorization header to your backend server. For example:
// Example of calling an endpoint with a JWT
import Userfront from "@userfront/react";
Userfront.init("demo1234");
async function getInfo() {
const res = await window.fetch("/your-endpoint", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Userfront.accessToken()}`,
},
});
console.log(res);
}
getInfo();
To handle a request like this, your backend should read the JWT from the Authorization header and verify that it is valid using the public key found in your Userfront dashboard.
Here is an example of Node.js middleware to read and verify the JWT access token:
// Node.js example (Express.js)
const jwt = require("jsonwebtoken");
function authenticateToken(req, res, next) {
// Read the JWT access token from the request header
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401); // Return 401 if no token
// Verify the token using the Userfront public key
jwt.verify(token, process.env.USERFRONT_PUBLIC_KEY, (err, auth) => {
if (err) return res.sendStatus(403); // Return 403 if there is an error verifying
req.auth = auth;
next();
});
}
Using this approach, any invalid or missing tokens would be rejected by your server. You can also reference the contents of the token later in the route handlers using the req.auth object:
With this information, you can perform further checks as desired, or use the userId or userUuid to look up user information to return.
For example, if you wanted to limit a route to admin users only, you could check against the authorization object from the verified access token, and reject any tokens that don’t have an admin role:
With your Toolkit forms in place, you can add social identity providers like Google, Facebook, and LinkedIn to your React application, or business identity providers like Azure AD, Office365, and more.
You do this by creating an application with the identity provider (e.g. Google), and then adding that application’s credentials to the Userfront dashboard. The result is a modified sign on experience:
No additional code is needed to implement Single Sign On using this approach: you can add and remove providers without updating your forms or the way you handle JWTs.
Final notes
React authentication and access control can be complex to do yourself, or it can be simple when using a service.
Both the setup step and, more importantly, the maintenance over time, are handled with modern platforms like Userfront.
JSON Web Tokens allow you to cleanly separate your auth token generation layer from the rest of your application, making it easier to reason about and more modular for future needs. This architecture also allows you to focus your efforts on your core application, where you are likely to create much more value for yourself or your clients.
For more details on adding auth to your React application, visit the Userfront guide, which covers everything from setting up your auth forms to API documentation, example repositories, working with different languages and frameworks, and more.
It is extremely weird that the calculator apps, even the default ones baked into desktop operating systems, embrace the UI and UX of those little cheap-o plastic physical calculators. I like what Florens Verschelde’s Math teacher had to say:
I had a Math teacher who would ban pocket calculators that didn’t show both your input and its result at the same time. If a calculator couldn’t show this:
38 ÷ 1.2
= 31.666666666667
You couldn’t use it.
The article ends up being in praise of Soulver, which I agree is a nice modern take on the idea of calculations.
I wish it was on Setapp, as I’d probably use it. But I don’t do enough regular mathin’ to go for the full price (today, anyway).
This week Google announced further details of its plan to remove cookies from ad tracking. The strategy, which the ad giant expects to be fully implemented by 2022, has come about due to increasingly stringent privacy laws in a growing number of territories around the globe.
Google’s first step was the announcement in January of FLoC (Federated Learning of Cohorts). Google itself is still testing and fine-tuning the system, but in essence, Google will replace 3rd-party cookies in Chrome with groups of anonymized users.
Critics of the plan have questioned whether users will be genuinely anonymous or whether Google will be tracking individuals to group them properly. The answer came earlier this week in a low-key announcement of KaST.
What is KaST?
KaST (Key and Surface Tracking) is the first iteration of Google’s new tracking technology. It works entirely without cookies and is fully device-agnostic.
The technology behind KaST is surprisingly old. It was first trialed in 1987 as a simple process for auditing the input of stenographers. Although the latest version of the technology draws heavily on voice recognition software algorithms, the original version of KaST — software named TAAA (Typist Account Accuracy Audit) — predates modern voice recognition by at least two years.
KaST uses…biomechanical and cognitive patterns, identifying individual users based on their keystrokes.
Just as your voice has a unique, identifiable modulation — anyone who uses telephone banking will be familiar with speaking their password — so too does your biomechanical input.
When you type on a keyboard or a touchscreen, the force, speed, and accuracy with which you hit characters are dependent on two things: your cognitive process and the unique biomechanics of your hands (the bones, ligaments, and muscles).
For example, when I type WordPress, I almost always type it as WordPRess (with a capitalized R). That is one facet of my combined biomechanical and cognitive process.
KaST uses keyboards and touch screens to track combined biomechanical and cognitive patterns, identifying individual users based on their keystrokes.
Mobile Approaches to KaST
KaST is heavily reliant on BMaC (Bio-Mechanical and Cognitive) input. Although Google hasn’t released any data to support the accuracy of KaST, BMaC is known to be surprisingly accurate.
Reports suggest that the KaST algorithm is 89.7% effective for character strings of 12 characters or more, leaping to 97.6% for 19 characters or more on a single device. That makes it too inaccurate for high-end processes like security but well within the necessary margin of error for a non-critical process like serving ads.
Google will be able to identify you on any machine, on any device, in any context, as soon as you type 19 characters or more
When switching to a touch-screen device, the accuracy plummets to just 87.8%. This may be one reason Google has been low-key in its trumpeting of the new technology so far.
According to TechBeat, initial trials of the tri-axis position of a device (X, Y, and Z rotation) were abandoned as inaccurate. Still, even without those additional tracking signals, Google claims KaST on mobile will achieve ~94% accuracy by the 1st quarter of 2022.
What Does KaST Mean for Users?
Much like many of the algorithms that govern our daily lives, KaST will be largely invisible to most of us. Unlike cookies that can be legislated for and removed from a local machine, your BMaC is as inescapable as your DNA.
Where privacy concerns really grow is that your BMaC follows you from device to device. How you type at home is identical to how you type at work. Your personal and professional profiles are now instantly connectable; Google will be able to identify you on any machine, on any device, in any context, as soon as you type 19 characters or more.
KaST Prompts Pre-M1 MacBook Rush
Within 24 hours of KaST’s announcement, Apple stores were reporting rush orders of pre-M1 MacBook Pros. With some stores reportedly selling out late on Wednesday.
The rush came in the wake of a Reddit post — that has since been removed — that claimed that the notoriously bad butterfly keyboard on pre-M1 MacBook Pros circumvented KaST because the inaccuracy of the keystrokes, and the tendency of the keys to stick introduced a random element that disguised the end-user from the KaST algorithm.
Although the Reddit post is unsubstantiated, it transpires that M1 Mac owners may not be the lucky ones after all.
Should You Worry About KaST?
Advocates maintain that KaST — and Google’s wider FLoC strategy — are beneficial to users and the web as a whole. They claim that identifying users without 3rd party cookies does more to protect privacy than hinder it.
Opponents argue that in a digital world rife with user tracking, privacy compromises of this magnitude cannot be contemplated simply to enable more sophisticated ad-serving.
Despite KaST’s early stages of development, privacy concerns are mounting, and a campaign has been launched to regulate Google’s use of the technology.