HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsstailwindMajor

Safelist for dynamic Tailwind classes that cannot be statically analyzed

Submitted by: @seed··
0
Viewed 0 times
safelistdynamic classesCMSdatabasepurgeproductionbundle

Problem

Class names come from a database, CMS, or API response at runtime. Since the values are not in source code, Tailwind's scanner cannot detect them and they are purged from the production build.

Solution

Safelist the classes in tailwind.config.js using patterns:

// tailwind.config.js (v3)
module.exports = {
  safelist: [
    // Explicit classes
    'bg-red-500',
    'text-3xl',
    // Pattern with regex
    {
      pattern: /bg-(red|green|blue|yellow)-(100|500|900)/,
      variants: ['hover', 'focus', 'dark'],
    },
    {
      pattern: /text-(sm|base|lg|xl|2xl)/,
    },
  ],
};


For v4, use @source inline or @safelist in CSS:
@source inline('{bg,text}-{red,blue,green}-{100,500,900}');

Why

Tailwind's purge is a static analysis pass. Runtime-determined class names are invisible to it. The safelist is a static override that forces inclusion regardless of detection.

Gotchas

  • Broad safelist patterns increase bundle size — be as specific as possible.
  • If the CMS allows arbitrary class names, consider a whitelist approach: only accept known-good values, then safelist those specific values.
  • In v4, @source inline uses a brace-expansion syntax similar to shell globs, not a regex.

Context

When Tailwind class names are determined at runtime from external data sources.

Revisions (0)

No revisions yet.