shimotsu tech

Webフロントエンドエンジニア @ to-R inc.

Supabase の supabase.auth.api.setAuthCookie() での Cookie の保存について

Supabase では、認証状態の変更などに応じてトークンを Cookie にセットするためのメソッド supabase.auth.api.setAuthCookie(req: any, res: any): void が用意されています(厳密には、 GoTrue API を利用している)。

例えば、supabase.auth.onAuthStateChange((event, session) => {}) などで event を検知し、その中で上記のメソッドを実行するなどして、最新のセッション情報を Cookie に保管します。

import { NextApiRequest, NextApiResponse } from 'next'

import { supabase } from '@/lib/utils/supabaseClient'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  supabase.auth.api.setAuthCookie(req, res)
}

実際に実行すると、sb:token というキー名でトークンが保存されています。

f:id:zuboriradio:20220219152930j:plain

で、このsupabase.auth.api.setAuthCookie(req: any, res: any): void ですが、内部の実装は以下のようになっております。

/**
   * Set/delete the auth cookie based on the AuthChangeEvent.
   * Works for Next.js & Express (requires cookie-parser middleware).
   */
  setAuthCookie(req: any, res: any) {
    if (req.method !== 'POST') {
      res.setHeader('Allow', 'POST')
      res.status(405).end('Method Not Allowed')
    }
    const { event, session } = req.body
    if (!event) throw new Error('Auth event missing!')
    if (event === 'SIGNED_IN') {
      if (!session) throw new Error('Auth session missing!')
      setCookie(req, res, {
        name: this.cookieOptions.name!,
        value: session.access_token,
        domain: this.cookieOptions.domain,
        maxAge: this.cookieOptions.lifetime!,
        path: this.cookieOptions.path,
        sameSite: this.cookieOptions.sameSite,
      })
    }
    if (event === 'SIGNED_OUT') deleteCookie(req, res, this.cookieOptions.name!)
    res.status(200).json({})
  }

ここで1点気にしておきたいのが、Cookie Options です。特に maxAge の部分。

export interface CookieOptions {
  // (Optional) The name of the cookie. Defaults to `sb:token`.
  name?: string
  // (Optional) The cookie lifetime (expiration) in seconds. Set to 8 hours by default.
  lifetime?: number
  // (Optional) The cookie domain this should run on. Leave it blank to restrict it to your domain.
  domain?: string
  path?: string
  // (Optional) SameSite configuration for the session cookie. Defaults to 'lax', but can be changed to 'strict' or 'none'. Set it to false if you want to disable the SameSite setting.
  sameSite?: string
}

Cookie の maxAge のデフォルト値は8時間となっており、基本的にはこの値は変更できないようです。 つまり、8時間後に sb:tokenCookie は消えてしまうので、それまでの間にトークンをリフレッシュする必要がありそうです。

なお、どうしても Cookie Options を変更したい場合、Client を別途生成して指定する方法もあるようなので、こちらが参考になりそうです。

github.com