Sending cookies to my backend in middleware issue?
Unanswered
LaPerm posted this in #help-forum
LaPermOP
I am rolling my own auth and have an updateSession() function in my middleware that checks if I have accessToken cookie if I do fine. If not then it sends a request to my backend to refresh the token (as long as a refresh token cookie is present).
I had to change from axios as it did not work in this environment I beleive it's running in the edge due to the middleware? Does this explain why my cookies aren't being send to my node backend?
import { cookies } from 'next/headers';
import { jwtDecode } from 'jwt-decode';
import { User } from '@/types/user';
import { env } from '../../config/env';
export function getSession() {
const accessToken = cookies().get('accessToken')?.value;
if (!accessToken) return null;
return jwtDecode<User>(accessToken);
}
export async function updateSession() {
const accessToken = cookies().get('accessToken')?.value;
try {
if (accessToken) return;
await refreshSession();
} catch (error) {
console.log(error);
throw error;
}
}
export async function refreshSession() {
try {
const response = await fetch(
`${env.NEXT_PUBLIC_SERVER_ENDPOINT}/api/sessions/refresh`,
{
credentials: 'include',
}
);
const data: { accessToken: string } = await response.json();
return data.accessToken;
} catch (error) {
console.log(error);
return null;
}
}I had to change from axios as it did not work in this environment I beleive it's running in the edge due to the middleware? Does this explain why my cookies aren't being send to my node backend?
export async function middleware(request: NextRequest) {
await updateSession();
....rest of my code
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};5 Replies
@LaPerm I am rolling my own auth and have an updateSession() function in my middleware that checks if I have accessToken cookie if I do fine. If not then it sends a request to my backend to refresh the token (as long as a refresh token cookie is present).
import { cookies } from 'next/headers';
import { jwtDecode } from 'jwt-decode';
import { User } from '@/types/user';
import { env } from '../../config/env';
export function getSession() {
const accessToken = cookies().get('accessToken')?.value;
if (!accessToken) return null;
return jwtDecode<User>(accessToken);
}
export async function updateSession() {
const accessToken = cookies().get('accessToken')?.value;
try {
if (accessToken) return;
await refreshSession();
} catch (error) {
console.log(error);
throw error;
}
}
export async function refreshSession() {
try {
const response = await fetch(
`${env.NEXT_PUBLIC_SERVER_ENDPOINT}/api/sessions/refresh`,
{
credentials: 'include',
}
);
const data: { accessToken: string } = await response.json();
return data.accessToken;
} catch (error) {
console.log(error);
return null;
}
}
I had to change from axios as it did not work in this environment I beleive it's running in the edge due to the middleware? Does this explain why my cookies aren't being send to my node backend?
export async function middleware(request: NextRequest) {
await updateSession();
....rest of my code
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
yes the middleware always runs on the edge environment, but this is not related to the cookies issue. the middleware runs on the server-side and there are no cookies store there, cookies are stored on the client's browser. if you want to send the client's cookies in your
fetch request you need to read them from the request and add them manually in the fetch headers@Rafael Almeida yes the middleware always runs on the edge environment, but this is not related to the cookies issue. the middleware runs on the server-side and there are no cookies store there, cookies are stored on the client's browser. if you want to send the client's cookies in your `fetch` request you need to read them from the request and add them manually in the `fetch` headers
LaPermOP
Thank you I managed to get token back although my backend sets a new cookie ideally which is not working either is that again due to the environment I’m running it in?
May need to rethink how i update this token
the middleware should be able to set cookies: https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
@Rafael Almeida the middleware should be able to set cookies: <https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies>
LaPermOP
Thank you I think I have a better idea what's happening now. I now set the new token in the middleware rather than my 'official' backend.
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const isPublicPath = publicPaths.some(pattern => pattern.test(path));
const isProtectedPath = protectedPaths.some(pattern => pattern.test(path));
const newToken = await updateSession();
const response = NextResponse.next();
if (newToken) {
response.cookies.set({
name: 'accessToken',
value: newToken,
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 1000 * 60 * 15,
});
}
const isLoggedIn = !!request.cookies.get('accessToken')?.value;
....rest of code
return response;
}