agentleFS
Piyush8296Piyush8296/claude-workspace/.claude/skills/auth-patterns/SKILL.md

auth-patterns

Skill2 starsChanged 6 months agoMITView on GitHub

Authentication and authorization patterns for React and Next.js — NextAuth/Auth.js setup, middleware route protection, token refresh, session management, protected components, OAuth providers, role-based UI. Use when implementing login, protecting routes, or managing user sessions.

We split this skill into the rules it gives an agent

1 rule. 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 4 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Rule: Never store auth tokens in localStorage or sessionStorage.

    line 16

“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Auth Patterns

Architecture Decision

ApproachBest ForSession Storage
NextAuth / Auth.jsNext.js apps, OAuth providersServer-side (JWT or database)
Custom JWTReact SPAs, custom backendshttpOnly cookie (server-set)
Session cookieTraditional server-renderedhttpOnly cookie

Rule: Never store auth tokens in localStorage or sessionStorage. Always use httpOnly cookies.

Next.js Middleware Protection

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

const PUBLIC_ROUTES = ['/', '/login', '/register', '/forgot-password'];
const AUTH_ROUTES = ['/login', '/register'];  // Redirect away if already logged in

export async function middleware(req: NextRequest) {
  const token = await getToken({ req });
  const { pathname } = req.nextUrl;

  // Already authenticated → redirect away from auth pages
  if (token && AUTH_ROUTES.some((r) => pathname.startsWith(r))) {
    return NextResponse.redirect(new URL('/dashboard', req.url));
  }

  // Not authenticated → redirect to login (except public routes)
  if (!token && !PUBLIC_ROUTES.some((r) => pathname === r || pathname.startsWith('/api/auth'))) {
    const loginUrl = new URL('/login', req.url);
    loginUrl.searchParams.set('callbackUrl', pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|public/).*)'],
};

NextAuth Setup

// lib/auth.ts
import NextAuth from 'next-auth';
import Google from 'next-auth/providers/google';
import Credentials from 'next-auth/providers/credentials';
import { env } from '@/lib/env';

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google({
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
    }),
    Credentials({
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      authorize: async (credentials) => {
        const user = await verifyCredentials(credentials);
        if (!user) return null;
        return { id: user.id, email: user.email, name: user.name, role: user.role };
      },
    }),
  ],
  callbacks: {
    jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        token.role = user.role;
      }
      return token;
    },
    session({ session, token }) {
      session.user.id = token.id as string;
      session.user.role = token.role as string;
      return session;
    },
  },
  pages: {
    signIn: '/login',
    error: '/login',
  },
});

Session Hook

// hooks/useAuth.ts
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';

export function useAuth({ required = false } = {}) {
  const { data: session, status } = useSession({ required });
  const router = useRouter();

  return {
    user: session?.user ?? null,
    isAuthenticated: !!session?.user,
    isLoading: status === 'loading',
    role: session?.user?.role ?? 'guest',
    signOut: () => {
      signOut({ callbackUrl: '/login' });
    },
  };
}

Protected Components

// components/ProtectedRoute.tsx
'use client';

import { useAuth } from '@/hooks/useAuth';

interface ProtectedRouteProps {
  children: React.ReactNode;
  requiredRole?: string;
  fallback?: React.ReactNode;
}

export function ProtectedRoute({ children, requiredRole, fallback }: ProtectedRouteProps) {
  const { isAuthenticated, isLoading, role } = useAuth({ required: true });

  if (isLoading) return fallback ?? <LoadingSkeleton />;
  if (!isAuthenticated) return null;  // Middleware handles redirect
  if (requiredRole && role !== requiredRole) return <ForbiddenState />;

  return <>{children}</>;
}

// Role-based UI rendering
export function RoleGate({ allowed, children }: { allowed: string[]; children: React.ReactNode }) {
  const { role } = useAuth();
  if (!allowed.includes(role)) return null;
  return <>{children}</>;
}
// Usage
<ProtectedRoute requiredRole="admin">
  <AdminDashboard />
</ProtectedRoute>

<RoleGate allowed={['admin', 'editor']}>
  <EditButton />
</RoleGate>

React SPA (Custom JWT)

For plain React without Next.js:

// lib/auth.ts
import { create } from 'zustand';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  checkSession: () => Promise<void>;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  isAuthenticated: false,

  login: async (email, password) => {
    // Server sets httpOnly cookie, returns user object
    const user = await fetchClient<User>('/api/auth/login', {
      method: 'POST',
      body: { email, password },
    });
    set({ user, isAuthenticated: true });
  },

  logout: async () => {
    await fetchClient('/api/auth/logout', { method: 'POST' });
    set({ user: null, isAuthenticated: false });
  },

  checkSession: async () => {
    try {
      const user = await fetchClient<User>('/api/auth/me');
      set({ user, isAuthenticated: true });
    } catch {
      set({ user: null, isAuthenticated: false });
    }
  },
}));

Security Rules

  • Tokens in httpOnly, Secure, SameSite=Strict cookies only
  • Short-lived access tokens (15 min) + long-lived refresh (7 days)
  • Validate auth server-side on every request, not just client-side
  • Logout must invalidate server session, not just clear client state
  • Rate-limit login attempts (5/min per IP)
  • Hash passwords with bcrypt/argon2, never SHA/MD5
  • CSRF tokens on state-changing requests if using cookies

Integration with Other Skills

  • api-layer: Auth interceptor for token injection
  • error-handling: AuthError class, redirect on 401
  • security-audit: Token storage, CSRF, rate limiting
  • state-management: Auth state in Zustand store

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.