I am creating an application in sveltekit, trying to protect my routes through the use of hooks or middleware, but when I am logged in and try to enter an unprotected route, I want to redirect to the /home address, however I get an error and no I understand what I’m doing wrong
I have this hook in sveltekit.
hooks.server.js
import 'dotenv/config';
import { redirect } from '@sveltejs/kit';
import jwt from 'jsonwebtoken';
const unProtectedRoutes = ['/', '/registro', '/registro/pn','/registro/pj','/forgotmail','/forgot'];
const SECRET_KEY = process.env.SECRET_KEY;
export const handle = async ({ event , resolve}) => {
console.log(event.url.pathname);
console.log(process.env.SECRET_KEY);
const token = event.cookies.get('access_token');
console.log(token);
if (!token && !unProtectedRoutes.includes(event.url.pathname)) {
console.log('NETRE pIRMERRRRRRRRRRRRR IF');
redirect(303, '/');
}
if (token) {
try {
console.log('NETRE SEGUNDOOOO IF');
// Verificar el token
const decoded = jwt.verify(token, SECRET_KEY , { algorithms: ['RS256'] } );
console.log(decoded);
//const userId = decoded.id;
if (event.url.pathname === '/logout') {
console.log('entre logoutF');
event.cookies.delete('access_token', { path: '/' });
redirect(303, '/');
}
if (unProtectedRoutes.includes(event.url.pathname)) {
console.log('SI esta en la');
redirect(303, '/home');
}
} catch (error) {
console.error('Error al verificar el token:', error);
event.cookies.delete('access_token', { path: '/' });
redirect(303, '/');
}
}
return resolve(event);
};
For some reason in this “if” an error occurs, and it fails to redirect to the route “/home”, finally this error is caught by my try/catch , and it ends up redirecting me to the route “/”
if (unProtectedRoutes.includes(event.url.pathname)) {
console.log('SI esta en la');
redirect(303, '/home');
}
I have tried using Response, but it doesn’t work the way I want
return new Response(null, {
status: 303,
headers: {
location: '/home'
}
});
Jose Martin Castro Agüero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.