pacocoursey / next-themes

Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing
https://next-themes-example.vercel.app/
MIT License
4.94k stars 177 forks source link

Is there a way to initialize the theme by fetching theme (on the server side) from a database? #48

Open animeshchat opened 3 years ago

animeshchat commented 3 years ago

Thanks for the great library.

My app has different themes that are stored in the user's account. How can I fetch the theme on the server side and then set the theme in next-themes? Or does this need to be set into local storage directly?

pacocoursey commented 3 years ago

Good question. Next-themes doesn't support this in a nice way right now, and it may not need to.

It sounds like you're server-rendering all your pages, so you can just include the theme as a body class with the initial HTML payload (getInitialProps in _document I believe). Then you don't need localStorage or the render-blocking inline script that next-themes injects.

animeshchat commented 3 years ago

@pacocoursey - Thanks for your reply!

My web app has a combination of server side and client side rendering, and supports multiple themes. The user may have saved theme preference, which needs to be fetched.

If no themes preferences are present for the user, the app will rely on the system defaults. You're right - maybe I don't need to use localStorage but its useful when it comes to propagating changes across tabs/sessions.

next-themes was really useful for the above reasons. Saved me from the task of building in all that logic.

If only it could support a way to set initial theme. For eg.

**<ThemeProvider initTheme="dark" attribute="class">** 

Currently., I am fetching the preference on the server side and setting the theme (setTheme()) on the client side, which is causing the frontend to flash.