better server side signin redirects

this makes it so if a user requests a page (not API route) and isn't
signed in, it automatically redirects them to the sign in page (doesn't
show a flash of the error page)
This commit is contained in:
DecDuck
2024-10-23 12:55:38 +11:00
parent c4a3e4e9a7
commit ef13b68592
4 changed files with 136 additions and 88 deletions

View File

@ -0,0 +1,24 @@
import { H3Error } from "h3";
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook("error", async (error, { event }) => {
if (!event) return;
// Don't handle for API routes
if (event.path.startsWith("/api")) return;
// Make sure it's a web error
if (!(error instanceof H3Error)) return;
switch (error.statusCode) {
case 401:
case 403:
const userId = await event.context.session.getUserId(event);
if (userId) break;
return sendRedirect(
event,
`/signin?redirect=${encodeURIComponent(event.path)}`,
);
}
});
});