Skip to content

docs: auth guard middleware template (better-auth integration) #630

Description

@SisyphusZheng

Summary

Provide an official auth guard middleware template showing how to protect routes using better-auth (or any cookie-session library) with openElement's loader/action model. The better-auth recipe doc exists but lacks a route-guard integration example.

Competitive context

Framework Auth approach
SvelteKit Recipe (Lucia/better-auth in hooks.server.js handle)
Next.js Recipe (Clerk/Auth.js in middleware.ts) + CVE-2025-29927 lesson: middleware-only auth is insufficient
Astro Recipe (Lucia in onRequest)
Fresh Recipe (custom in _middleware.ts)
openElement better-auth doc exists; no guard template

Key lesson from Next.js CVE-2025-29927: middleware-only auth can be bypassed. Guard logic must also run in the loader/action, not just at the edge.

Proposed deliverable

  1. Guard middleware template (docs/integrations/auth-guard.md):
// app/middleware/auth-guard.ts
export function requireAuth(c, next) {
  const session = await getSession(c.req);
  if (!session) {
    if (c.req.header('x-openelement-action')) {
      return c.json({ type: 'redirect', status: 303, location: '/login' }, 303);
    }
    return c.redirect('/login', 303);
  }
  c.set('user', session.user);
  await next();
}
  1. Loader-level double-check (defense in depth):
export const loader = async ({ request }) => {
  const user = await getUser(request); // re-verify, don't trust middleware alone
  if (!user) throw redirect('/login');
  return { user };
};
  1. Protected route file convention documentation

Non-goals

  • No @openelement/auth package
  • No OAuth implementation
  • No session store (stays with better-auth)

Target version

0.43.0 (documentation + template)

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions