Skip to content

Instantly share code, notes, and snippets.

@silvesterwali
Last active April 15, 2024 14:14
Show Gist options
  • Select an option

  • Save silvesterwali/4c4a415e9e76dc666bb01cbaf510d082 to your computer and use it in GitHub Desktop.

Select an option

Save silvesterwali/4c4a415e9e76dc666bb01cbaf510d082 to your computer and use it in GitHub Desktop.
Nuxt3 Composable for handle simple auth

create file composable useRequestOptions.ts

useRequestOptions.ts

import type { AuthCredential } from "@/types";
export default function () {
  const config = useRuntimeConfig();

  const defaultRedirect = "/sign-in";

  const credential = useCookie<AuthCredential | null>("auth-token", {
    expires: new Date(Date.now() + 12096e5), // 2 weeks from now
    sameSite: "lax",
    path: "/",
    watch: true,
  });

  async function clearCredential() {
    if (process.client) {
      useCookie("auth-token").value = null;
      window.location.replace(defaultRedirect);
    }
  }
  function onRequest(context: any) {
    context.options.headers = context.options.headers || {};
    context.options.headers.authorization = credential.value?.token
      ? "Bearer " + credential.value?.token
      : "";
  }
  function onResponseError(context: any) {
    if (context.response.status === 401) {
      return clearCredential();
    }
  }

  const requestOptions = {
    baseURL: config.public.API_ENDPOINT,
    onRequest: (contex: any) => onRequest(contex),
    onResponseError: (context: any) => onResponseError(context),
  };
  return {
    requestOptions,
  };
}

in your page or component

<template>
  <pre>{{data}}</div>
</template>

<script setup>

const { requestOptions } = useRequestOptions();

const {
  data,
  error,
  refresh,
} = await useAsyncData("blogs", () =>
  $fetch(`/blogs`, {
    method: "get",
    ...requestOptions,
  })
);

// or 

const {data}=await useFetch('/blog',{
  ...requestOptions
})


</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment