I have build middleware with Next.js and Kinde. My protected route is ‘/profile’.
import { withAuth } from '@kinde-oss/kinde-auth-nextjs/server';
export default function middleware(req: Request) {
return withAuth(req);
}
export const config = {
matcher: ['/profile'],
};
import UserCard from '@/app/_components/user-card/user-card';
import { getUserFromDB } from '@/db/queries/user';
import { getKindeServerSession } from '@kinde-oss/kinde-auth-nextjs/server';
import classes from './Profile.module.css';
export default async function Profile() {
const { getUser } = getKindeServerSession();
const user = await getUser();
if(user === null) {
redirect('/login')
}
const user = await getUserFromDB(kindeUser.id);
return (
<div className={classes.profile}>
<UserCard user={user} />
</div>
);
}
But when I call from ‘/profile’ I still get that user can be null. In what case that user can be null? Also what would be good solution when user is null? I would prefer not to write if(user===null) redirect('/login)
in every component that needs getUser()
function and is part of protected routes.
Is it ok to consider that user is not null if check from middleware is ok?
I expect that user is not null if getUser()
is called in protected route.