1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nuxt3のサーバサイドで複数Cookieをまとめて取得する

Last updated at Posted at 2024-10-09

2024年10月現在の情報となります。
頻繁に更新があるため、利用の際には公式ドキュメントを参照するようお願いします。

useCookieでCookieを取得

Nuxt3にはCookieを取得するためのuseCookieというComposablesが用意されています。

useCookie · Nuxt Composables

const cookie = useCookie(name, options)

ただし、キー名指定で1個ずつしか取得できません。

複数Cookieを取得

useRequestHeadersが使えます。

useRequestHeaders · Nuxt Composables

cookies.ts
const headers = useRequestHeaders(['cookie'])

これを利用したComposablesの実装例です。

useFetchCookie.ts
export const useFetchCookie = async () => {

  // SSRの場合はリクエストにcookieを手動追加
  const headers: HeadersInit = useRequestHeaders(['cookie'])

  const { data, status, execute } = useFetch('/api/path', {
    method: 'GET',
    headers: headers,
  })
  
  return {
    data: readonly(data),
    status: readonly(status),
    execute
  }
}

H3Eventを利用できるとき

getHeader(event, 'Cookie')が使えます。
@supabase/ssrcreateServerClientを宣言する際に必要なgetAllとかで使えます。

useSupabase.ts
import { CookieOptions, createServerClient, parseCookieHeader } from '@supabase/ssr'
import type { H3Event } from 'h3'

export const useSupabase = async (event: H3Event) => {
  const config = useRuntimeConfig()
  const supabase = createServerClient(
    config.supabaseUrl,
    config.supabaseAnonKey,
    {
      cookies: {
        getAll: () => parseCookieHeader(getHeader(event, 'Cookie') ?? ''),
        setAll: (
          cookies: {
            name: string
            value: string
            options: CookieOptions
          }[],
        ) => cookies.forEach(({ name, value, options }) => setCookie(event, name, value, options)),
      }
    }
  )

  return { supabase }
}

(余談)useRequestHeadersを見つける前の話

useCookieの実装を見に行きます。

exportされていないreadRawCookiesというメソッドがあるみたいなので、追ってみると次の記述が見つかります。

cookie.ts
function readRawCookies (opts: CookieOptions = {}): Record<string, unknown> | undefined {
  if (import.meta.server) {
    return parse(getRequestHeader(useRequestEvent()!, 'cookie') || '', opts)
  } else if (import.meta.client) {
    return parse(document.cookie, opts)
  }
}

getRequestHeader(useRequestEvent()!, 'cookie')で取れるようです。

実装例
useFetchCookie.ts
import { getRequestHeader } from 'h3'

export const useFetchCookie = async () => {

  // SSRの場合はリクエストにcookieを手動追加
  const cookies = import.meta.server ? getRequestHeader(useRequestEvent()!, 'cookie') : undefined
  const headers: HeadersInit = cookies ? { Cookie: String(cookies) } : {}

  const { data, status, execute } = useFetch('/api/path', {
    method: 'GET',
    headers: headers,
  })
  
  return {
    data: readonly(data),
    status: readonly(status),
    execute
  }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?