Obfuscate Tailwind classes in a Laravel project

Yusuf
Geek Culture
Published in
3 min readMay 26, 2021

We’re going to see how to obfuscate Tailwind classes, and CSS classes in general, in a Laravel project so that no one is able to simply copy and paste your classes and steal your work. The goal is to transform class="bg-indigo-500 flex flex-col h-full" to something like class="h N T ja". Beautiful, isn’t it?

Let’s start by running npm install postcss-rename --save-dev. You can check the repository here for more information. That’s the plugin responsible for renaming our CSS classes.

Configuring the plugin in Laravel’s Mix is easy. The key point here is to save the class mappings to a Laravel config file, which we will use later on. Basically, this config file will contain key-value pairs similar to 'bg-indigo-500' => 'h'.

I am using Sass and Tailwind here, but it doesn’t matter at all. Correctly configuring the plugin for our needs is the most important part. Here is my Mix file:

webpack.mix.js

When you execute npm run prod, you should now have the config\map.php file containing what I described earlier. Note that I am using the keyword map for the sake of simplicity, but you are free to rename it.

config\map.php

The next step is to make use of this generated file. You may simply map your classes by calling config('map.bg-indigo-500'), and you’re ready to go but hey, it’s kind of problematic if you need to wrap all your classes like that, it also does not consider the environment.

We’ll now create a helper function with it’s corresponding Blade directive. Here’s the helper function. You may search how to create a helper file if you don’t already have one. Note that we are checking if we’re in production.

app\helper.php

And here is the Blade directive.

app\Providers\AppServiceProvider.php

You are now left with updating your Blade views. Wrapping the content of class attributes with the new directive is enough.

For example,

<div class=“rounded p-3 bg-gray-800”>

Should become,

<div class=“@map('rounded p-3 bg-gray-800')”>

If you think that the configuration I am using generates too short class names (which may potentially lead to collisions), you can always play with it as you wish. For instance, you may generate random class names:

webpack.mix.js

Output sample for using randomly generated class names of 5 characters length:

Obfuscating Tailwind classes
config\map.php

I hope you found this writing useful. Feel free to share your way of doing things. :)

Don’t hesitate to follow me on Twitter for more hacks. If you build SaaSes with Laravel, you may also find this post on sharing sessions interesting.

--

--

Yusuf
Geek Culture

Software Engineer. Working with Java/Spring and PHP/Laravel. Building APIs and SaaSes. Occasionally playing with matrices.