くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

NuxtでCookieを扱うならuniversal-cookieがよさそう

Cookieを扱うライブラリはいろいろあるけど、
サーバでもクライアントでも使えるuniversal-cookieが良さそうだった。

使い方もシンプルでいい感じ。

インストール

$ npm i universal-cookie

使い方はこんな感じ

import { IncomingMessage } from "http";
import Cookies from "universal-cookie";

const KEY_TOKEN = "__session";
const options = {
  path: "/",
  secure: process.env.NODE_ENV === "production",
  sameSite: process.env.NODE_ENV === "production",
  maxAge: 60 * 60 * 24 * 7, // 1week
};

class MyCookie {
  public setToken(token: string | null, req?: IncomingMessage) {
    const cookies = new Cookies(!!req ? req.headers.cookie || undefined : undefined);
    cookies.set(KEY_TOKEN, token, options);
  }

  public getToken(req?: IncomingMessage): string | null {
    const cookies = new Cookies(!!req ? req.headers.cookie || undefined : undefined);
    return cookies.get(KEY_TOKEN) || null;
  }

  public removeToken(req?: IncomingMessage) {
    const cookies = new Cookies(!!req ? req.headers.cookie || undefined : undefined);
    cookies.remove(KEY_TOKEN);
  }
}

export const myCookie = new MyCookie();

クライアントのときは、reqをundefinedで呼び出して、サーバのときはreqを設定して呼び出させばOK。

以上!!

参考にしたサイト