Middleware PerformanceReview request
Answered
Asiatic Lion posted this in #help-forum
Asiatic LionOP
hi everyone, this is my middleware for now as beggining to the app, and im requesting to see if its bad pracctice or its good, or if it can be improved in a way, feel free to review it:
Answered by Saint Hubert Jura Hound
Yeah i get u but the way ur doing it right now, if there is no token it will still attempt to run the rest of the function. Using !token and returning allows u to break out early
81 Replies
Its fine, however, for better readibility and to add more roles, I'd create a object for roles and loop through it
Asiatic LionOP
please can ik ur years of exp ? iid u dont mind, also for the roles, they said its fixed
With react/express, about 1.5-3 years, and with next.js, almost a year
Asiatic LionOP
well
Asiatic LionOP
any other review
Bengal
You don't want the user saved as a global variable. The middleware runs on the server and the very first request sets the user for all the following requests (on that server)
it would be better to store that information in some kind of JWT, or http secure cookie
Asiatic LionOP
its stored in jwt token, im decoding it with the getUserInfo request to my custom backend
@Asiatic Lion its stored in jwt token, im decoding it with the getUserInfo request to my custom backend
Saint Hubert Jura Hound
I think what he means is the user is saved in the user var, and ur updating the user if it doesnt exist yet and if theres a token, but on the next request there will already be a user stored in the user variable, so it wont call getUserInfo again
Asiatic LionOP
thats what i want
to make less requests on the backend
i have a separate server, and im getting the userInfo only if i dont have the user Info yet
just to not always call the same api and get the same info again and again
@Asiatic Lion thats what i want
Saint Hubert Jura Hound
Did u test what would happen if u have multiple users making requests?
Asiatic LionOP
its not every user will have its own app ?
@Asiatic Lion its not every user will have its own app ?
Saint Hubert Jura Hound
No, theres only one server. The function will be run again for each request. But the user variable is defined outside the function scope
Either way you should validate your cookies/tokens for each request anyways
Asiatic LionOP
so on each request i have to get my user info ?
its not too much unused load on the server
@Asiatic Lion so on each request i have to get my user info ?
Saint Hubert Jura Hound
Yes, each request that requires authentication u validate the session
@Asiatic Lion its not too much unused load on the server
Saint Hubert Jura Hound
Itll be fine, when you get thousands of users, then u can start worrying about load and scale horizontally
Asiatic LionOP
but the backend is already validating my session on the request, so if its not valid it will return a 401
its not the case here ?
@Asiatic Lion but the backend is already validating my session on the request, so if its not valid it will return a 401
Saint Hubert Jura Hound
Ur backend is just returning user data based on the token. The validation is happening in ur middleware. If you wanna make authenticated requests to ur backend eventually, you will also need to implement authentication on ur backend seperately, also through middleware
Asiatic LionOP
yea that's the case here
the backend already made a middleware
Asiatic LionOP
also its very weird stuff, he wants me to pass the token is a custom header named "auth-token" and not in the Authorization headers
Umm, whats the problem with that?
Asiatic LionOP
i dont say its a problem, but why not following the recommneded practice
but in my case, while my backend already have a middleware, and im doing the logic of the middleware only from my side, so the middleware i've pasted here is fine ?
@Asiatic Lion but in my case, while my backend already have a middleware, and im doing the logic of the middleware only from my side, so the middleware i've pasted here is fine ?
Saint Hubert Jura Hound
Test it with multiple users
Log the user information in the nextjs middleware
Youll see what i mean
Asiatic LionOP
okayy
Asiatic LionOP
get u know
@Saint Hubert Jura Hound Test it with multiple users
Asiatic LionOP
ur right, when im on the same build, the user remain the same in the logs
so decoding the token on my side will be better solution ?
or always validating the token from the backend is better ?
what is better
@Asiatic Lion ur right, when im on the same build, the user remain the same in the logs
Saint Hubert Jura Hound
Just move the user declaration to inside the scope of the middleware function
Asiatic LionOP
yea i did it
now im asking on what is better, decoding the token in the backend using an api call, or decode it manually inside the middleware
Saint Hubert Jura Hound
Oh
Idk i dont see why u couldnt just do it in the middleware. No need to make an extra api call just to decode it
can u review it please
@Asiatic Lion https://gist.github.com/kamel996/7243b90644517bd01b8da00ecf9f6430
Saint Hubert Jura Hound
Yeah looks good only thing i would change is
If(!token) throw error
And declare the user var with a const below that
No need to use let since ur not changing the user object
If(!token) throw error
And declare the user var with a const below that
No need to use let since ur not changing the user object
Or if !token return rather
Asiatic LionOP
im doing that because if !token there is some public routes
the user can access
Saint Hubert Jura Hound
Yeah i get u but the way ur doing it right now, if there is no token it will still attempt to run the rest of the function. Using !token and returning allows u to break out early
Answer
Saint Hubert Jura Hound
Use return NextResponse.next()
Asiatic LionOP
can u just adjust it in the gist ?
Saint Hubert Jura Hound
if(!token){
return NextResponse.next()
}Asiatic LionOP
yea i made it like that
above the const user = await getUserInfo(token.value)
Saint Hubert Jura Hound
Yup sounds good to me
Be sure to always test authentication stuff well though
Asiatic LionOP
now the issue is requesting the token validation to the backend server on each next request, i think i should decode it manually or idk if there is a way to avoid decoding it always
Saint Hubert Jura Hound
Well idrk what ur getUserInfo endpoint does but theres nothing wrong with making an api call in ur middleware.
I personally use supabase and validate the session using their auth service on every request in the middleware
I personally use supabase and validate the session using their auth service on every request in the middleware
Asiatic LionOP
it takes my token, validates and decodes it and return back the user info to me
i mean its not a huge thing on ther server so because on each page i want to access, i have to call this endpoint ? u dont see it a problem ?
Saint Hubert Jura Hound
Yeah u could probably just do that in ur middleware
@Asiatic Lion i mean its not a huge thing on ther server so because on each page i want to access, i have to call this endpoint ? u dont see it a problem ?
Saint Hubert Jura Hound
But no theres no problem with that
Asiatic LionOP
thanks a lot for ur time mate
Saint Hubert Jura Hound
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function updateSession(request: NextRequest) {
let response = NextResponse.next({
request: {
headers: request.headers,
},
})
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return request.cookies.get(name)?.value
},
set(name: string, value: string, options: CookieOptions) {
request.cookies.set({
name,
value,
...options,
})
response = NextResponse.next({
request: {
headers: request.headers,
},
})
response.cookies.set({
name,
value,
...options,
})
},
remove(name: string, options: CookieOptions) {
request.cookies.set({
name,
value: '',
...options,
})
response = NextResponse.next({
request: {
headers: request.headers,
},
})
response.cookies.set({
name,
value: '',
...options,
})
},
},
}
)
await supabase.auth.getUser()
return response
}Heres an example from supabase docs u can see they check auth on every request too
@Asiatic Lion thanks a lot for ur time mate
Saint Hubert Jura Hound
No worries bro good luck
Asiatic LionOP
can i know how many years of exp u got ?
@Saint Hubert Jura Hound Heres an example from supabase docs u can see they check auth on every request too
Asiatic LionOP
yea i can see
Saint Hubert Jura Hound
With coding in general? A few years on and off. 4 or 5 total probably. With nextjs about 8 months i think
Asiatic LionOP
well good luck in ur career mate
again thanks for ur time
Saint Hubert Jura Hound
U too have a good one!
U can mark this post as solved btw :)
Asiatic LionOP
yea ur right, also i may ask other question in other post about the decoding thing
idk how to mark as solved
is it closing it ?
Original message was deleted
Saint Hubert Jura Hound
^