User Session
Learn how to use user session in NEXTDEVKIT
How to Use
After configuring NextDevKit's Auth settings, you can start learning how to use the built-in methods to get user information.
We won't go deep into how NextDevKit implements login, signup, forgot password, etc. You can refer to the corresponding code:
- login -
src/components/auth/login-form.tsx - signup -
src/components/auth/signup-form.tsx - forgot password -
src/components/auth/forgot-password-form.tsx - reset password -
src/components/auth/reset-password-form.tsx - social signin -
src/components/auth/social-signin.tsx
If you have more complex login/registration flows, you can extend based on existing code.
How to Get User Information
Here we mainly introduce how to use NextDevKit's Auth functionality to get user information, check user sessions, and login status, etc.
In most business cases, you need at least two auth-related functions:
- Check if user is logged in to decide whether to show corresponding features.
- Get user information to display corresponding user details.
NextDevKit comes with a pre-configured useSession hook to get user information and check if user is logged in.
NextDevKit provides multiple methods to get user authentication information, suitable for different use cases. As a template user, it's important to understand when to use which method. Let me introduce each method's purpose and best practices in detail.
1. Using Authentication Info in Client Components
useSession Hook (Recommended)
This is the main method for getting user information in client components, based on React Context and React Query.
For example, if we want to implement a user information display component, we can use useSession to get user information (the code below is just an example, not implemented in the template):
"use client";
import { useSession } from "@/lib/hooks/use-session";
export function UserProfile() {
const { user, session, loaded, reloadSession } = useSession();
// Show loading skeleton to avoid flashing
if (!loaded) {
return <Skeleton className="h-10 w-full" />;
}
// User not logged in
if (!user || !session) {
return redirect("/auth/login");
}
// User logged in
return (
<div>
<h1>Welcome, {user.name}!</h1>
<p>Email: {user.email}</p>
<p>Locale: {user.locale}</p>
{/* Call when need to reload session */}
<button onClick={() => reloadSession()}>
Refresh Session
</button>
</div>
);
}When to use useSession:
- ✅ When you need user information in client components
- ❌ Don't use in server components
Important notes:
- Always check
loadedstate first to avoid flashing effects - Check if
userandsessionexist before using - Call
reloadSession()after user information updates to refresh state and avoid expired user info
Direct authClient Usage (Advanced)
If you need more control or want to perform auth-related operations, you can use authClient directly:
"use client";
import { authClient } from "@/lib/auth/client";
import { useRouter } from "next/navigation";
const handleLogout = async () => {
try {
await authClient.signOut();
router.push("/login");
} catch (error) {
console.error("Logout failed:", error);
}
};When to use authClient:
- ✅ When performing login, registration, logout operations
- ✅ When calling specific authentication APIs
- ✅ When you need more granular error handling
- ✅ When you don't want React Query to manage auth state
2. Using Authentication Info in Server Components
getSession Function (Server-only)
Use this method to get user information in server components, server actions, and API routes:
Using in Server Actions:
"use server";
import { getSession } from "@/lib/auth/server";
const session = await getSession();
if (!session?.user) {
throw new Error("Unauthorized");
}When to use getSession:
- ✅ When you need user information in server components
- ✅ When verifying user identity in server actions
- ✅ When getting current user information in API routes
- ❌ Don't use in client components
3. Using Authentication Info in Edge Runtime
Edge getSession (For Middleware and Edge Functions)
Use in middleware.ts or other Edge runtime environments:
import { getSession } from "@/lib/auth/edge";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
const session = await getSession(request);
// Protect specific routes
if (request.nextUrl.pathname.startsWith("/app")) {
if (!session?.user) {
const loginUrl = new URL("/auth/login", request.url);
loginUrl.searchParams.set("redirectTo", request.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/app/:path*"]
};When to use Edge getSession:
- ✅ When verifying user identity in middleware.ts
- ✅ When getting user information in Edge API routes
- ✅ When needing auth info in edge computing environments
- ✅ Can also use server getSession after latest Next.js updates to nodejs middleware
Use Case Summary Table
| Use Case | Recommended Method | Reason |
|---|---|---|
| Get user info in client components | useSession() | Provides loading state and reload functionality |
| Execute auth operations in client | authClient | Direct access to authentication API |
| Protect routes in server components | getSession() | Server-only, better performance |
| Verify identity in server actions | getSession() | Secure server-side verification |
| Route protection in middleware | Edge getSession() | Edge runtime compatible |
Common Errors and Solutions
1. "useSession must be used within SessionProvider" error
Cause: Using useSession in a component not wrapped by SessionProvider
Solution: Make sure your app is properly wrapped by Provider, check layout.tsx
2. Using client hooks in server components
// ❌ Wrong - using client hook in server component
export default function ServerComponent() {
const { user } = useSession(); // This will error
return <div>{user?.name}</div>;
}
// ✅ Correct - using server method
export default async function ServerComponent() {
const session = await getSession();
return <div>{session?.user?.name}</div>;
}3. Using wrong getSession in middleware
// ❌ Wrong - using server method in middleware, will cause database connection failure
import { getSession } from "@/lib/auth/server"; // Wrong import
// ✅ Correct - using Edge version
import { getSession } from "@/lib/auth/edge";By following these guidelines, you can correctly and efficiently use the authentication system in NextDevKit. Remember to always choose the appropriate method based on your usage environment and handle loading states and error cases properly.