I have frontend on Nextjs 14 app router and a backend in nodejs, that set http only jwt cookie in header when the user login to the app. Then I have a function getMe() in the middleware, that gets the profile info. If http only is set correctly, getMe() send a response type success, if is not, it gives failure. Then I check, if it is success, the user can access to his profile, if is not, middleware must redirect him to the sign-in page.
The problem is that, the response of the getMe function gives me a null. But when I test it just copy and pasting url to the browser, it works.
Can you help me with this issue?
Here is the code i provided below:
import { apiUrl } from '@/constants/apiUrl';
import { User, UserData } from '@/types/auth';
import { typedFetchJSON } from '@/utils/typedFetch';
export function signIn(username: string, password: string) {
return typedFetchJSON(`${apiUrl}/user/signin`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ username, password }),
});
}
export function getMe() {
return typedFetchJSON<User>(`${apiUrl}/user/me`, {
credentials: 'include',
});
}
import { createI18nMiddleware } from 'next-international/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { getMe } from './api/auth';
const locales = ['ru', 'tm', 'en', 'tr'];
const I18nMiddleware = createI18nMiddleware({
locales,
defaultLocale: 'ru',
});
export async function middleware(request: NextRequest) {
const protectedPaths = ['/profile', '/add-ads'];
if (protectedPaths.includes(request.nextUrl.pathname.slice(3))) {
try {
const response = await getMe();
if (response?.type !== 'success') {
console.log('response getMe');
return NextResponse.redirect(new URL('/sign-in', request.url));
}
} catch (error) {
console.error('Failed to fetch user profile:', error);
}
}
return I18nMiddleware(request);
}
export const config = {
matcher: [
'/((?!api|static|.*\..*|_next|favicon.ico|robots.txt|serviceworker.js).*)',
],
};