Next.js Discord

Discord Forum

DB-calls in middleware

Answered
Tiphiid wasp posted this in #help-forum
Open in Discord
Avatar
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
View full answer

65 Replies

Avatar
They are working hard for Node.js runtime support for middlewares
https://github.com/vercel/next.js/discussions/71727
Check out this discussion
Avatar
Tiphiid waspOP
So I should just wait?
Avatar
Nope, what's the purpose of db calls in the middleware in your project?
auth maybe?
Avatar
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
Avatar
what kind of auth provider are you using?
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
Avatar
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
Avatar
then create your api routes and you should be able to make requests to them from your middleware
Answer
Avatar
Tiphiid waspOP
Thanks I thought about that. So I should do this until this feature is implemented?
Since it will increase latency
Avatar
I also hope they will ship that feature in the near future!
Avatar
Tiphiid waspOP
Thanks. So I should just create an api-route for that which can only be accessed from the localhost?
Avatar
only be accessed from the localhost? wdym?
api routes are public by default
Avatar
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?
Avatar
yeah, it's correct
sever to server
Avatar
Tiphiid waspOP
I thought it would be good for security so that no one else can acces the api
Avatar
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
Avatar
Tiphiid waspOP
Ofcourse yes, I just meant that I check in the route if it is a server to server request
Avatar
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
Avatar
Tiphiid waspOP
So just an api route to validate the token right? That makes sense, sorry
Avatar
yeah
I meant as long as you check the token - you don't need to check request origin
Avatar
Tiphiid waspOP
Thanks a lot. Oh and should I encrypt opaque tokens in any way?
Avatar
I guess you have your own logic to encrypt/decrypt your tokens?
to get unique id of your users
Avatar
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
Avatar
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
I wouldn't recommend this
Avatar
Tiphiid waspOP
Sorry, thanks alot, I'll create a new one
So should I mark the solution now?
Avatar
yeah, for sure
@Tiphiid wasp
Avatar
Tiphiid waspOP
Thanks a lot for the help, really
Avatar
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
Avatar
Sorry not trying to necro a closed thread just wanted to add some helpful information, we locally host all of our stuff
Avatar
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?
Avatar
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.
Avatar
oh that's nice
but OP had sort of tricky auth logic and it required db query
Avatar
Depends with with strategy you wanna go with. I can share my middleware tomorrow morning when I get up to give you perspective.
Avatar
well if it's edge compatible it should be obvious, but yeah, would like to see other's solution
Avatar
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.
Avatar
🤣
Avatar
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
Avatar
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