DB-calls in middleware
Answered
Tiphiid wasp posted this in #help-forum
Tiphiid waspOP
What would be the best way to make an api call in middleware? Since prisma, mongodb and nanoid for auth are not supported in the edge runtime
Answered by James4u (Tag me if needed)
then create your api routes and you should be able to make requests to them from your middleware
65 Replies
They are working hard for Node.js runtime support for middlewares
https://github.com/vercel/next.js/discussions/71727
Check out this discussion
https://github.com/vercel/next.js/discussions/71727
Check out this discussion
Tiphiid waspOP
So I should just wait?
Nope, what's the purpose of db calls in the middleware in your project?
auth maybe?
Tiphiid waspOP
Yup right
Actually I use a combination of two tokens: one for the client (session based totally in the db and cached in memory) and an api-refresh-token (also totally in db and cached). For the api-token I use a jwt that is renewed with the refresh token
what kind of auth provider are you using?
in fact, in app router, you can choose alternative way for authentication
in fact, in app router, you can choose alternative way for authentication
import { redirect } from 'next/navigation'
import { createClient } from '@/utils/supabase/server'
export default async function PrivatePage() {
const supabase = await createClient()
const { data, error } = await supabase.auth.getUser()
if (error || !data?.user) {
redirect('/login')
}
return <p>Hello {data.user.email}</p>
}
this is an example from official supabase doc
oh okay got it
so you implemented your own auth
Tiphiid waspOP
I'm trying to challenge my self and learn the technologies behind it
Ik it probably wont be as safe, but I want to understand what I'm doing first
then create your api routes and you should be able to make requests to them from your middleware
Answer
Tiphiid waspOP
Thanks I thought about that. So I should do this until this feature is implemented?
Since it will increase latency
I also hope they will ship that feature in the near future!
Tiphiid waspOP
Thanks. So I should just create an api-route for that which can only be accessed from the localhost?
only be accessed from the localhost? wdym?
api routes are public by default
Tiphiid waspOP
I mean when I make the request from middleware, which is on the system. So its basically a request to the server itself
Or am I getting something terribly wrong?
yeah, it's correct
sever to server
Tiphiid waspOP
I thought it would be good for security so that no one else can acces the api
I mean, request from middleware from your api route is server to server
but by default api routes are public meaning you can always access to the api routes from anywhere
Tiphiid waspOP
Ofcourse yes, I just meant that I check in the route if it is a server to server request
I don't think you need a check for that in your api route
you can decrypt the token - and do your stuff
if you failed to decrypt - throw 401
Tiphiid waspOP
So just an api route to validate the token right? That makes sense, sorry
I meant as long as you check the token - you don't need to check request origin
Tiphiid waspOP
Thanks a lot. Oh and should I encrypt opaque tokens in any way?
I guess you have your own logic to encrypt/decrypt your tokens?
to get unique id of your users
Tiphiid waspOP
I really just use as a string to identify the user. I store token to user mappings in my db, so I can easily revoke them on compromise
anyway @Tiphiid wasp things are away from the original question
feel free to post another thread with your further questions
also don't mark solution to close this thread
feel free to post another thread with your further questions
also don't mark solution to close this thread
I wouldn't recommend this
Tiphiid waspOP
Sorry, thanks alot, I'll create a new one
So should I mark the solution now?
yeah, for sure
@Tiphiid wasp
Tiphiid waspOP
Thanks a lot for the help, really
If your locally hosting your stuff, there is zero issue with fetching in your middleware, if your hosting through vercel or some serverless provider, you 100% shouldnt do fetches in your middleware. When your locally or hosting via VPS and you do a fetch its still within the same box, so very little added performance degredation
Sorry not trying to necro a closed thread just wanted to add some helpful information, we locally host all of our stuff
No worries, appreciate for sharing your thoughts
Then what would you recommend if I host on vercel and you know middleware doesn't support node.js runtime as for now
make a custom middleware and wrap my pages and api routes?
I’d recommend going with an authentication strategy that does involve fetching from middleware there are options depending on how you wanna do it.
I don’t have to fetch to validate a users session in middleware. If you use Jose and jwts with a rsa key you can validate jwt tokens in middleware without any fetching.
I use to fetch every time but learned that Jose is edge compatible.
oh that's nice
but OP had sort of tricky auth logic and it required db query
Depends with with strategy you wanna go with. I can share my middleware tomorrow morning when I get up to give you perspective.
well if it's edge compatible it should be obvious, but yeah, would like to see other's solution
Yeah, that just couldn’t be done in middleware. Nextjs best practice would be to use a wrapper like you said. Simply because middleware doesn’t let you continue till you get passed along, whereas a wrapper you could do the fetch prior to streaming anything in but you would get the page load and skeleton going so it would be a better user experience. At least that’s my understanding of why they recommend it.
I am responsible for an enterprise application the company use… I don’t have to worry about users complaining about load times, I’ll tell ‘em to pound sand. 😂
It’s not super obvious with Jose. But I’ll share it anyways in the morning.
I think most people would advise against db calls in middleware
I do commend you for rolling your own auth though, its super important to know how it all works. Libraries obfuscate the logic so people dont learn
Tiphiid waspOP
Yeah i tried at first, but I was worried that you can't revoke tokens so easily. And that it was near impossible to tell the client that his access token expired and that he should request a new on (all that in an page route, not api route)
Thanks, i thought so too