내가 자꾸 까먹어서 쓰는 개발 이야기/Vue.js

Vue 3 Composition API: route 가드 설정 전 인증 체크하기

FIL. 2024. 4. 26. 10:54
728x90

상황은 이렇다.

 

  • Laravel의 sanctum을 통해 토큰을 받는 인증 방식을 채택
  • Pinia 스토어를 통해 인증 상태를 저장
  • 저장된 인증 상태를 확인하는 route guard 사용

먼저 main.ts 에서 앱에 route가 주입되기 전에 인증 상태를 확인해야 한다.

axios의 then 내부에서 app.use(router); 를 시도하니 오류가 발생했다.

따라서 axios를 async로 호출하여 강제로 토큰 확인이 완료된 후에 진행되도록 했다.

const authenticated = async (): Promise<AxiosResponse | undefined> => {
  try {
    return axios.get('/user/me');
  } catch (e) {
    return undefined;
  }
};

const auth: AxiosResponse | undefined = await authenticated();

if (auth !== undefined) {
  userStore.setUser(auth.data.user);
}

app.use(router);

 

router/index.ts 에는 Pinia에서 제공한 가이드대로 beforeEach() 내부에서 store를 호출하도록 했다.

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();

  if (to.name === 'dashboard' && !userStore.authenticated) {
    return next('/');
  } else if ((to.name === 'home' || to.name === 'login') && userStore.authenticated) {
    return next('dashboard');
  }

  next();
});

 

한가지 팁으로 알게된것은, Pinia store의 state 또는 getter를 storeToRefs를 통해 분해할당 하면 브라우저 콘솔에는 ComputedRefImpl 오브젝트가 찍힌다.

콘솔에서 확인할땐 .value를 붙이고, 코드에 실제 사용할땐 .value 없이 사용하면 된다고 한다.