Dynamic Token addon for Statamic 3, by Webographen

Using Dynamic Token in Statamic 3 and full static caching

Published July 1st, 2021

Important: The information in this article is over 12 months old, and may be out of date or no longer relevant.

But hey, you're here anyway, so give it a read see if it still applies to you.

I really do love Statamic’s full static caching for helping make a site feel incredibly snappy. Basically it caches a static HTML version of each page, and can be invalidated by specific actions within the control panel, or manually by running an ever-so-polite please command.

But it has one downside: dynamic content - such as randomised content, and also forms. Static is just that, static.

While this add-on doesn’t address the randomising of content (although the Mity Digital site has achieved that with the client logos through another method), it does tackle forms in statically cached sites.

The Dynamic Token add-on for Statamic 3 by webographen makes it really easy to have all of your pages statically cached - even those with forms - but still have fresh tokens.

There are two conditions though:

  1. Your site must be in a browser that has JavaScript enabled, and

  2. You must be using either ajax for your submissions, or have a redirect on submit

How to install?

Installation is really easy - a composer command, adding a tag to your form layout and updating your cache config - easy.

First of all, install:

1composer require webographen/statamic-dynamic-token

Up next, add the new dynamic_token tag to your view:

1{{ dynamic_token }}

And finally, update your config/statamic/static_caching.php file to remove your form views (if you were not caching them) from your exclude key, so that something like this:

1'exclude' => [
2 '/contact'

Becomes this:

1'exclude' => [],

Deploy, and you’re done. It all just works.

Why does my form need to be ajax or redirect for submitting?

Static caching is just that - it renders and stores a static version of each page. And that means the necessary CSRF token is not updated one each page load because the cached version is being served.

By using ajax for submissions, you can work around this as your JavaScript is doing the actual submitting - and that isn’t cached statically.

Or, by using the redirect and error_redirect parameters on your form layout - check out the form:create tag for more.

This is such a simple and easy to use add-on for Statamic 3 - and now means clients can add a form to any page - including one statically cached - and not have to have any site config changes in order for the form to work. Happy days!

You may be interested in...