#Hey guys..
1 messages · Page 1 of 1 (latest)
https://nextjs.org/docs/app/building-your-application/routing/middleware
You can use middleware and pass the auth props down to the page and use the data where you need it
Yeah I tried this..
The issue is it starts to break alot of things..
Because you'd have to mange states so far up the tree
Appreciate the correction!
I'll check it out. Brb
didn't mean that as a callout btw, but it's a common thing I see and can lead to lots of issues 😅 ❤️
Uhm.. what if I'm not using api routes..
It applies to all route segments
on matching paths
Any authentication/authorization happens in middleware.
For user data on the page, it could be as simple as a server component fetching from the database directly. (This would get cached and de-duped automatically)
Okay, that makes sense....
But there's one more little issue..
And maybe I'd figure it out when I read more on the nextjs middleware.. but just incase..
Here it is.. request to every authenticated endpoints on the external api needs an access token...
How do I manage this access token?
Normally, states would have been the Goto.. but it seems like a messy solution
You could just read* a cookie. Any future fetch() requests will include that cookie from the same origin
You would set the cookie on your login server action
Yeah...
I thought of setting it as a secured cookie so it can't be accessed by javascript(to prevent some sort of attack)...
But the issue is.. it's a bearer token...
I have to get the token and send it in the request header not as a request cookie...
You're accessing a 3rd party api? or jwt check?
3rd party api
So I am supposed to send the access token along the request header..
So it expects the token in the request header..
you can just pull it from the cookies server-side and include it in your fetch() headers to the external api
might be worth wrapping fetch as a server-only function for the utility
Okay.. sounds reasonable..
Thanks alot.
Hey..
So, I've gotten a little idea on what to do
So I'm using a middleware to check for authenticated user before proceeding
And I've wrapped my fetch as a server action..
But I'm facing a little issue..
I'm trying to change the cookie and it keeps saying
Cookies can only be modified in a Server Action or Route Handler
Which I don't understand why.. since the fetch is a server action
And I've wrapped my fetch as a server action..
I'd need to see code for this
Okay here it is
"use server"
import dayjs from "dayjs"
import jwtDecode from "jwt-decode"
import { cookies } from "next/headers"
import renewAccessToken from "../helpers/refresh_token"
import { NextResponse } from "next/server"
const TOKENNAME = "token"
const setCookie = (value) => ({
name: TOKENNAME,
value,
secure: true,
httpOnly: true,
path: "/"
})
export async function serverFetch(...args) {
let [resource, config] = args
// *****todo Interceptor for request begins here
// get access token from cookie and then make request to resource
const cookieStore = cookies()
let token = cookieStore.get(TOKENNAME)
if(!token) {
// ?user is not validated, redirect to authentication (login screen)
// find a way to go to auth screen
return
}
// ?Ensure that at the moment the token is not yet expired
const { exp } = jwtDecode(token.value)
const isExpired = dayjs.unix(exp).diff(dayjs()) < 1
if(isExpired) {
//? update token.
token = await renewAccessToken()
// ?Ensure it was a successful result
if(!token) {
// ?user is not validated, redirect to authentication (login screen)
// find a way to go to auth screen
}
// ?Set the access token to cookie
console.log(`here`)
NextResponse.json({}).cookies.set(setCookie(`hello`))
return NextResponse
}
// ?Procced with request
// *****Interceptor for request ends here
const response = await fetch(resource, config)
// *****todo Interceptor for response begins here
// Remember; The response object can only be consumed once, so, clone anytime we want to use in here
// *****Interceptor for response ends here
return response
}