Middleware not working?
Hi all,
i guess i have a very common use case. but as i am new to better auth maybe you can give me some hints.
Stack T3 Stack with better-auth, drizzle, trpc.
Usecase:
my app is a "backendonly" app which means that only the loginform is shown to the public.
next is: my users can have 2 different roles "user" and "admin"
any user has to login before he can see something.
- /page.tsx => Loginform
- /user/page.tsx => Protected Userpage
- /admin/page.tsx => Protected Adminpage
now the i tried to use a middleware to protect those routes:
middleware.ts
but i get this error when im logged in:
i already tried as well to add the runtime, but i get another error
so im thinking that it is not the preferrable way to protect routes.
can you give me some hints how to solve or implement such usecases.
is it better to write or use plugins?
Solution:Jump to solution
then i tried to use the code for older nextjs versions
```
const { data: session } = await betterFetch<Session>("/api/auth/get-session", {
baseURL: request.nextUrl.origin,
headers: {...
5 Replies
https://www.better-auth.com/docs/integrations/next#middleware
Only NextJs 15.2.0 or above support nodejs runtime. Below that you have to just check the existence of the cookie or make an HTTP call to get the full session object in middleware.
Next.js integration | Better Auth
Integrate Better Auth with Next.js.
im already on next 15.2.3 but its not gonna work
when i add it it shows
I haven't tried this yet on Nextjs15.2.xx. But I would suggest you to write the middleware as per the better auth doc and just check for existence of the session. Then in the beginning of each protected route do the check again by calling API. that would be the best both security and peformance wise.
i upgraded to next 15.3.2 and used the code for nextjs 15.2.0 and above. it still does not work.
Solution
then i tried to use the code for older nextjs versions
this works perfectly