@@ -448,10 +448,203 @@ apiShield: {
448448}
449449```
450450
451+ ## Server-Side Authentication
452+
453+ ### Using getCurrentUser() in API Routes
454+
455+ For server-side authentication in your API routes, use the ` getCurrentUser() ` function from the server-side ` useServerAuth() ` composable. This is essential for protecting API endpoints and accessing user data in server contexts.
456+
457+ ``` typescript
458+ // server/api/profile.get.ts
459+ import { useServerAuth } from ' #nuxt-users/server'
460+
461+ export default defineEventHandler (async (event ) => {
462+ const { getCurrentUser } = useServerAuth ()
463+ const user = await getCurrentUser (event )
464+
465+ if (! user ) {
466+ throw createError ({
467+ statusCode: 401 ,
468+ statusMessage: ' Authentication required'
469+ })
470+ }
471+
472+ return {
473+ profile: {
474+ id: user .id ,
475+ name: user .name ,
476+ email: user .email ,
477+ role: user .role ,
478+ lastLogin: user .last_login_at
479+ }
480+ }
481+ })
482+ ```
483+
484+ ### Role-Based API Protection
485+
486+ ``` typescript
487+ // server/api/admin/users.get.ts
488+ import { useServerAuth } from ' #nuxt-users/server'
489+
490+ export default defineEventHandler (async (event ) => {
491+ const { getCurrentUser } = useServerAuth ()
492+ const user = await getCurrentUser (event )
493+
494+ // Check authentication
495+ if (! user ) {
496+ throw createError ({ statusCode: 401 , statusMessage: ' Authentication required' })
497+ }
498+
499+ // Check authorization
500+ if (user .role !== ' admin' ) {
501+ throw createError ({ statusCode: 403 , statusMessage: ' Admin access required' })
502+ }
503+
504+ // Admin-only logic here
505+ const allUsers = await fetchAllUsers ()
506+ return { users: allUsers }
507+ })
508+ ```
509+
510+ ### User-Specific Data Access
511+
512+ ``` typescript
513+ // server/api/posts/my-posts.get.ts
514+ import { useServerAuth } from ' #nuxt-users/server'
515+
516+ export default defineEventHandler (async (event ) => {
517+ const { getCurrentUser } = useServerAuth ()
518+ const user = await getCurrentUser (event )
519+
520+ if (! user ) {
521+ throw createError ({ statusCode: 401 , statusMessage: ' Authentication required' })
522+ }
523+
524+ // Fetch posts belonging to the current user
525+ const userPosts = await fetchPostsByUserId (user .id )
526+ return { posts: userPosts }
527+ })
528+ ```
529+
530+ ### Optional Authentication
531+
532+ Some endpoints may provide different data based on authentication status:
533+
534+ ``` typescript
535+ // server/api/posts/public.get.ts
536+ import { useServerAuth } from ' #nuxt-users/server'
537+
538+ export default defineEventHandler (async (event ) => {
539+ const { getCurrentUser } = useServerAuth ()
540+ const user = await getCurrentUser (event ) // Returns null if not authenticated
541+
542+ const posts = await fetchPublicPosts ()
543+
544+ // Add extra data for authenticated users
545+ if (user ) {
546+ const postsWithUserData = posts .map (post => ({
547+ ... post ,
548+ isLiked: await checkIfUserLikedPost (user .id , post .id ),
549+ canEdit: post .author_id === user .id || user .role === ' admin'
550+ }))
551+ return { posts: postsWithUserData }
552+ }
553+
554+ // Return basic data for non-authenticated users
555+ return { posts }
556+ })
557+ ```
558+
559+ ### Database Operations with User Context
560+
561+ ``` typescript
562+ // server/api/comments.post.ts
563+ import { useServerAuth } from ' #nuxt-users/server'
564+ import { readBody } from ' h3'
565+
566+ export default defineEventHandler (async (event ) => {
567+ const { getCurrentUser } = useServerAuth ()
568+ const user = await getCurrentUser (event )
569+
570+ if (! user ) {
571+ throw createError ({ statusCode: 401 , statusMessage: ' Authentication required' })
572+ }
573+
574+ const { postId, content } = await readBody (event )
575+
576+ // Create comment with authenticated user's ID
577+ const newComment = await createComment ({
578+ post_id: postId ,
579+ author_id: user .id , // Use authenticated user's ID
580+ content ,
581+ created_at: new Date ()
582+ })
583+
584+ return { comment: newComment }
585+ })
586+ ```
587+
588+ ### Middleware Pattern
589+
590+ Create reusable authentication middleware:
591+
592+ ``` typescript
593+ // server/utils/authMiddleware.ts
594+ import { useServerAuth } from ' #nuxt-users/server'
595+ import type { UserWithoutPassword } from ' nuxt-users/utils'
596+
597+ export const requireAuth = async (event : any ): Promise <UserWithoutPassword > => {
598+ const { getCurrentUser } = useServerAuth ()
599+ const user = await getCurrentUser (event )
600+
601+ if (! user ) {
602+ throw createError ({
603+ statusCode: 401 ,
604+ statusMessage: ' Authentication required'
605+ })
606+ }
607+
608+ return user
609+ }
610+
611+ export const requireRole = async (event : any , requiredRole : string ): Promise <UserWithoutPassword > => {
612+ const user = await requireAuth (event )
613+
614+ if (user .role !== requiredRole ) {
615+ throw createError ({
616+ statusCode: 403 ,
617+ statusMessage: ` ${requiredRole } access required `
618+ })
619+ }
620+
621+ return user
622+ }
623+ ```
624+
625+ Then use the middleware in your API routes:
626+
627+ ``` typescript
628+ // server/api/admin/dashboard.get.ts
629+ import { requireRole } from ' ~/server/utils/authMiddleware'
630+
631+ export default defineEventHandler (async (event ) => {
632+ const adminUser = await requireRole (event , ' admin' )
633+
634+ // Admin-only logic here
635+ return {
636+ message: ` Welcome admin ${adminUser .name }! ` ,
637+ stats: await getAdminStats ()
638+ }
639+ })
640+ ```
641+
451642## Checking Authentication Status
452643
453644For checking authentication status using the ` useAuthentication ` composable, refer to the [ Composables documentation] ( /user-guide/composables.md#useauthentication ) .
454645
646+ For accessing the current user in client-side components, see the [ ` getCurrentUser() ` documentation] ( /user-guide/composables.md#getcurrentuser ) .
647+
455648## Error Handling
456649
457650For error handling with the ` useAuthentication ` composable, refer to the [ Composables documentation] ( /user-guide/composables.md#useauthentication ) .
0 commit comments