본문 바로가기
Program/Front-end

[tailwindcss] cookie darkmode with nextjs

by pishio 2023. 1. 6.


nextjs에서 cookie를 활용해서 darkmode를 적용 했다.

브라우저에서 먼가를 저장할수 있는 곳은
localstorage, sessionstorage, cookie, history를 활용 할 수 있다.

이중 쿠키를 사용한 이유는 다음과 같다.

* localstorage를 사용할 경우 SSR에서는 localstorage에 접근 할 수 없다.
client side로딩 시점에 localstorage를 로드해서 theme를 적용하면
로딩 딜레이가 있기 때문에, 화면이 깜빡이는 현상이 발생하게 된다.

화면이 깜빡임 없이 theme를 적용하기 위해 cookie는 좋은 방안이다.

nextjs SSR에서 cookie에 접근이 가능하기 때문이다.

import { cookies } from 'next/headers';
import './globals.css';


export default function RootLayout({ children }) {
  const theme = cookies().get('theme');

  function getThemeColor() {
    return theme ? (theme.value === 'dark' ? '#262626' : '#ffffff') : '#ffffff';
  }

  function getThemeClass() {
    return theme ? (theme.value === 'dark' ? 'dark' : null) : null;
  }

  return (
    <html lang="en" className={getThemeClass()}>
      <head>

        <meta name="theme-color" content={getThemeColor()} />
      </head>

      <body className="bg-white dark:bg-neutral-800">
        {children}
      </body>
    </html>
  );
}


댓글