// the router creates front-end endpoints and serves pages to them import { createRouter, createWebHistory } from "vue-router"; import LoginForm from "../pages/LoginForm.vue"; import RegisterForm from "../pages/RegisterForm.vue"; import ItemsList from "../pages/ItemsList.vue"; import ItemForm from "../pages/ItemForm.vue"; import UsersList from "../pages/UsersList.vue"; import index from "../pages/index.vue"; import { authStorage } from "../api/axios.ts" // link path to the page component const routes = [ { path: "/", component: index }, { path: "/login", component: LoginForm }, { path: "/register", component: RegisterForm }, { path: "/items", component: ItemsList, meta: { requiresAuth: true } }, { path: "/item/new", component: ItemForm, meta: { requiresAuth: true } }, { path: "/item/:id", component: ItemForm, meta: { requiresAuth: true } }, { path: "/users", component: UsersList, meta: { requiresAuth: true } } ]; // I really like this const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: routes, }); // intercept before routing router.beforeEach((to, from, next) => { const token: string | null = authStorage.getAccessToken(); if(to.meta.requiresAuth && !token) { // if the page requires use to be signed in, they must have at least a token set next("/login"); } else { next(); } }); // if the api responds unauthorized (401) then it also will auto-redirect to the login page export default router;