Cookie

In the below code example you can see how you can create a cookie composable and how you can use this in your Nuxt 3 app.

use-stateful-cookie.ts
import type { CookieOptions } from '#app'

/**
 * Manage a stateful cookie
 *
 * This composable should not be necessary when this issue is fixed:
 * https://github.com/nuxt/framework/issues/2416
 */
export default function useStatefulCookie<T>(
  name: string,
  options?: CookieOptions<T>
) {
  const cookie = useCookie<T>(name, options as CookieOptions<T> & { readonly?: false | undefined; })
  const state = useState<T>(name, () => cookie.value)

  watch(
    state,
    () => {
      cookie.value = state.value
    },
    {
      deep: true
    }
  )

  return state
}
authentication-cookie.ts
export const useAuthenticationCookie = () => {
  const expires = new Date()
  expires.setFullYear(expires.getFullYear() + 1)

  return useStatefulCookie<
    Pick<
      AccessToken,
      "access_token" | "refresh_token" | "expires_in" | "id_token"
    >
  >("token", {
    expires
  })
}
example usage: use-auth.ts
export const useAuth = () => {
  const config = useRuntimeConfig() // get Nuxt config options
  const cookie = useAuthenticationCookie()

  const authHeaders = () => {
      return computed(() => ({
        ...(cookie.value && {
          Authorization: `Bearer ${cookie.value.access_token}`,
          api_key: config.apiKey
        })
      }))
    }
}