1
Usage in Server Components
You can now call getCurrentUser() in any server component to get the current authenticated user:
import {getCurrentUser} from "@/lib/session";
const currentUser = await getCurrentUser();
if (!currentUser) {
// handle unauthenticated state
}
console.log(currentUser.role, currentUser.subscription);
2
Content of getCurrentUser Function
It's a cached async function to retrieve the current user:
export const getCurrentUser = cache(async () => {
const tokens = await getTokens(await cookies(), authConfig);
if (!tokens) return null;
const user = toUser(tokens);
const db = getFirestore(getFirebaseAdminApp());
const snapshot = await db
.collection('users')
.doc(user.uid)
.get();
const userSubscription = await getUserSubscriptionPlanById(user.uid);
if (snapshot.exists) {
const data = snapshot.data();
user.role = data?.role;
user.subscription = userSubscription;
}
return user;
});
This function:
- Retrieves authentication tokens from cookies.
- Converts the tokens to a user object.
- Fetches additional user data from Firestore.
- Loads the user's subscription plan.
- Returns the complete user object, or
nullif the user is not authenticated.
For more advanced server-side authentication patterns and middleware options, refer to the next-firebase-auth-edge documentation. This will help you customize authentication and token handling according to your app's needs.