How to enforce user's to set certain user properties?

Hi, I've been thinking on this for a while now. How do I force user's after the first login (or possibly on admin reset) to set certain attributes like a username? Right now I use a middleware, but I read in the docs that this might not be the best idea (and also for some reason the middleware stopped working after my last prod update). In Next.js middleware, it's recommended to only check for the existence of a session cookie to handle redirection. To avoid blocking requests by making API or database calls.
export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<TSessionWithoutUsername>('/api/auth/get-session', {
baseURL: env.NEXT_PUBLIC_SERVER_URL,
headers: {
cookie: request.headers.get('cookie') || '', // Forward the cookies from the request
},
});

// Not logged in → do nothing
if (!session) return NextResponse.next();

// Logged in, but no username → redirect to /choose-username
if (!session.user.username) {
const url = request.nextUrl.clone();
url.pathname = PATHS_CONFIG.choose_username;
return NextResponse.redirect(url);
}

return NextResponse.next();
}
export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<TSessionWithoutUsername>('/api/auth/get-session', {
baseURL: env.NEXT_PUBLIC_SERVER_URL,
headers: {
cookie: request.headers.get('cookie') || '', // Forward the cookies from the request
},
});

// Not logged in → do nothing
if (!session) return NextResponse.next();

// Logged in, but no username → redirect to /choose-username
if (!session.user.username) {
const url = request.nextUrl.clone();
url.pathname = PATHS_CONFIG.choose_username;
return NextResponse.redirect(url);
}

return NextResponse.next();
}
This "problem" can be generalized into other problems like user needs to accept terms, user needs to do a onboarding... How would you implement something like that? I also though about putting a check in root layout - but also here the nextjs docs says "Reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations."
Solution:
Database | Better Auth
Learn how to use a database with Better Auth.
Jump to solution
1 Reply
Solution
Ping
Ping2w ago
Database | Better Auth
Learn how to use a database with Better Auth.

Did you find this page helpful?