K
Kinde•2w ago
ninzamax

Frequent logouts

I am using kinde auth with nextjs and react,but for some reasons I keep getting logged out intermittently. I can see the refresh tokens and access token setup properly in the cookies. At some point the Kinde auth provider hits this api, api/auth/setup and its returns not logged in. So I have to click on login again but authentication flow is not there, it will login me straight without email and passcode. What could be the reasons for the intermittent sign outs , I am pretty sure I have set the id token , access token , refresh token for a 7 days , 30 days and 6 months. Any help is appreciated! Thanks
6 Replies
Yoshify
Yoshify•2w ago
What does your middleware setup look like?
ninzamax
ninzamaxOP•2w ago
Something like this:
import { NextRequest, NextResponse } from "next/server";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { RoleEnum } from "@prisma/client";
import { LOGIN_API } from "@/endpoint/endpoint";

export async function middleware(request: NextRequest) {
const { refreshTokens, getUser, getRoles } = getKindeServerSession();
await refreshTokens();

const user = await getUser();

if (!user) {
// return new NextResponse("Unauthorized", { status: 401 });
return NextResponse.redirect(new URL(LOGIN_API, request.url));
}

if (request.nextUrl.pathname.startsWith("/admin/")) {
const roles = await getRoles();
const allowedRoles = [
RoleEnum.ADMIN.toLocaleLowerCase(),
RoleEnum.SUPER_ADMIN.toLocaleLowerCase(),
];
const hasRequiredRole = roles?.some((role) =>
allowedRoles.includes(role.key)
);
const hasSuperAdminRole = roles?.some(
(role) => role.key.toLowerCase() === RoleEnum.SUPER_ADMIN.toLowerCase()
);

if (request.url.includes("admin/accounts")) {
if (!hasSuperAdminRole) {
return new NextResponse("Forbidden", { status: 403 });
}
}

if (!hasRequiredRole) {
return new NextResponse("Forbidden", { status: 403 });
}
}
return NextResponse.next();
}

export const config = {
matcher: ["/admin/:path*", "/api/openAI/:path*", "/user-settings"],
};
import { NextRequest, NextResponse } from "next/server";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { RoleEnum } from "@prisma/client";
import { LOGIN_API } from "@/endpoint/endpoint";

export async function middleware(request: NextRequest) {
const { refreshTokens, getUser, getRoles } = getKindeServerSession();
await refreshTokens();

const user = await getUser();

if (!user) {
// return new NextResponse("Unauthorized", { status: 401 });
return NextResponse.redirect(new URL(LOGIN_API, request.url));
}

if (request.nextUrl.pathname.startsWith("/admin/")) {
const roles = await getRoles();
const allowedRoles = [
RoleEnum.ADMIN.toLocaleLowerCase(),
RoleEnum.SUPER_ADMIN.toLocaleLowerCase(),
];
const hasRequiredRole = roles?.some((role) =>
allowedRoles.includes(role.key)
);
const hasSuperAdminRole = roles?.some(
(role) => role.key.toLowerCase() === RoleEnum.SUPER_ADMIN.toLowerCase()
);

if (request.url.includes("admin/accounts")) {
if (!hasSuperAdminRole) {
return new NextResponse("Forbidden", { status: 403 });
}
}

if (!hasRequiredRole) {
return new NextResponse("Forbidden", { status: 403 });
}
}
return NextResponse.next();
}

export const config = {
matcher: ["/admin/:path*", "/api/openAI/:path*", "/user-settings"],
};
Yoshify
Yoshify•2w ago
For passive refreshing of tokens to work when expiry is hit we need middleware to run on all paths - see the documentation An example matcher would be:
export const config = {
matcher: [
// Run on everything but Next internals and static files
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
]
};
export const config = {
matcher: [
// Run on everything but Next internals and static files
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
]
};
You can opt out paths by extending the matcher further, or by using the publicPaths option on middleware. For an example of that see here
Kinde docs
Next.js App Router SDK
Our developer tools provide everything you need to get started with Kinde.
ninzamax
ninzamaxOP•2w ago
@Yoshify Does it have something to do with intermittent logouts, I am experimenting by removing await refreshTokens() now
Yoshify
Yoshify•2w ago
Are you using pages router or app router? refreshTokens has no effect in app router environments. If you set up the middleware to run on all paths the effect of refreshTokens will be handled for you automatically in the background when tokens approach expiry. Also please make sure you're on the latest version (2.6.1) as there were further improvements to passive and on-demand refreshing in the latest release 🙂
Abdelrahman Zaki
Abdelrahman Zaki•5d ago
Hi Ninzamax, I just wanted to check if you were able to solve this by adding the middleware or is there something we can do to help?

Did you find this page helpful?