Need help using `vsf-customer` cookie in vsf2 extended with Nuxt3

21 views Asked by At

I am building an app in vsf2 using Nuxt 3 and magento2 integration. While trying to implement sinup and signin, I used following methods provided by the magento sdk:

createCustomer customer generateCustomerToken revokeCustomerToken

initially, I wanted to use vsf-customer to store cookies as recommended in the documentation but I couldn't find a way to implement it, all I know is that I have to register cookies in the middleware configurations. So, I used localStorage and all works fine but when I applied route guards using route middleware from nuxt, the page throws me 500 and only upon refreshing the page it redirects me to the login screen. Below is my code and some screenshots.

router middleware: [enter image description here](https://i.stack.imgur.com/rAaBk.png)

import { defineNuxtRouteMiddleware, navigateTo } from 'nuxt/app';

export default defineNuxtRouteMiddleware((to, from) => {
  let router = useRouter();
  let userToken = localStorage.getItem('customerToken');
  console.log(userToken, ' inside local storage');
  if (userToken == null) {
    return router.push('/login');
  }
});

Token Generator:

type generateCustomerTokenType = {
    email: string;
    password: string;
  };

  const generateCustomerToken = async (tokenObj: generateCustomerTokenType) => {
    const { data } = await useAsyncData(() => useSdk().magento.generateCustomerToken(tokenObj));
    console.log('Token data: ', data.value?.data?.generateCustomerToken?.token);
    return data;
  };

Login Logic:

const createLoginObj = () => ({
  email: email.value,
  password: password.value
})

type loginObjType = {
  email: string,
  password: string
}

const login = async () => {
  const loginObj: loginObjType = createLoginObj();
  try {
      const tokenData = await generateCustomerToken(loginObj);
      if (!tokenData.value?.errors) {
        const token: any = tokenData.value?.data?.generateCustomerToken?.token;
        localStorage.setItem('customerToken', token);
        await fetchCustomer();
        isLoading.value = false;
        router.push('/my-account');
      } else throw new Error(tokenData.value.errors[0].message);
    } catch (error) {
      console.log("An error occured: ", error);
      errorMsg.value = error as string;
      isLoading.value = false;
    } finally {
      isLoading.value = false;
    }
};

0

There are 0 answers