middleware.ts alternative
Unanswered
Tomistoma posted this in #help-forum
TomistomaOP
I'm using supabase and prisma client. I've been trying to use
So what are my alternatives , i know I can query the database myself from within react components and use redirects that way. However is this really the best way to go about it? Someone told me it's less secure than using
Thanks
middleware.ts but realised it's not possible because I can't run any database queries from middleware.ts so it won't be possible to retrieve user's session that way. I also don't want to slow down my whole site by making fetch requests within middleware.ts to my own API (I'm pretty sure that will negatively impact performance. Even the docs says not to make expensive fetch request within middleware.ts)So what are my alternatives , i know I can query the database myself from within react components and use redirects that way. However is this really the best way to go about it? Someone told me it's less secure than using
middleware.ts but I'm not sure what my options are. Thanks
2 Replies
Sun bear
I faced the same issue ans I just added the user role via callback to the session.
Make sure the callback is in a try catch block so that you dont get an error on edge.
Then in the middleware you can just get the session and access the user role.
Of course just in case the user role is what you need. I dont know what kind of user data you want to use
Make sure the callback is in a try catch block so that you dont get an error on edge.
Then in the middleware you can just get the session and access the user role.
Of course just in case the user role is what you need. I dont know what kind of user data you want to use
A somewhat safe way to do it would be to use server actions in your component(s)/pages(s).
heres an example:
heres an example:
"use server";
import { redirect } from 'next/navigation';
/*
Server action name: authenticate
Arguments:
- username (string)
Short summary:
- When the server action is called it will do an api request to some url (this could also be changed to be some database), when it receives an response and if its not OK then the user will be redirected to the login page, otherwise the json data of the api request will be returned.
*/
async function authenticate(username: string) {
const res = await fetch('https://...')
if (!res.ok) {
redirect('/login')
}
return res.json()
}