Write to session or cookie before page starts streaming
Unanswered
keremaydemir posted this in #help-forum
We use rest api with php backend. We have an autherization header that is needed for all requests. But, for this authorization token to be available we need to make a handshake request, and it gives us the token. I need to set this token somehow earlier than everything, so other requests work as expected. I tried middleware but it is setting cookie very late. I implemented next-auth for sign in, and I can set handshake token to session with callbacks, but when user visiting the page for the first time, they dont see anything because all requests are dependent to it. I would be very happy if you can help
.
. export default async (req: NextRequest): Promise<NextResponse> => {
const res = NextResponse.next();
let hsToken = req.cookies.get("handshake")?.value;
if (!hsToken) {
hsToken = await makeHandshake();
// need to set before api requests fired
res.cookies.set("handshake", hsToken);
}
return res;
};
HEADER FOR REST API REQUESTS
Authorization: `Bearer ${hsToken}`
2 Replies
So you want to check if user is already logged in and have access token or not ? If yes, you want be able to get api respond from server, am i wrong ?
if user is not logged in I also need the token, for example I make a fetch request to get all posts, if Autherization: "Bearer token" is attached to fetch request, then I can get the posts, otherwise it returns error.
If user visits for the first time this autherization token must be there without checking if user logged in or not. If user logs in, I solve the problem with sessions anyway.
If user visits for the first time this autherization token must be there without checking if user logged in or not. If user logs in, I solve the problem with sessions anyway.