Server Side Rendering of Tailwind CSS styles in NextJS
11/8/2022 •7.5K views •2 min read
NextJS provides us with SSR capabilities by rendering the page in the server.
Although, if you are Tailwind for styling, you'll notice that the styles are not applied on the server rendered pages.
For this to work, we need to enable an experimental feature in next.config.js
1 2 3 4 5 6
const nextConfig = { //... experimental: { optimizeCss: true, // enabling this will enable SSR for Tailwind }, };
We also need to install Critters
1
yarn add -D critters
Next.JS will internally use this library called Critters
Now, all you do is yarn build
and then yarn start
.
Make a Postman call and under "Preview" you could see that the Tailwind styles are now getting applied at the server!
Here are the before and after screenshots:
Before
You can see that no styles are applied on the server rendered page.
After
After the changes are made, you can see that the styles are applied on the server rendered page.
Gotcha:
If you are using the @tailwindcss/typography
plugin, you'd notice these warnings in your logs.
More info here