Authentication
How user authentication works in BloggFast and how to protect routes.
Last updated:
How authentication works
BloggFast uses Neon Auth for all user authentication via the @neondatabase/auth package. Authentication state is managed server-side through signed HTTP-only cookies, making it secure against XSS attacks.
The auth flow:
- User visits
/auth/sign-inor/auth/sign-up - Credentials are submitted to the Neon Auth API endpoint
- A signed session cookie is set using
NEON_AUTH_COOKIE_SECRET - Middleware reads and validates the session cookie on each protected request
- Unauthenticated requests to protected routes redirect to
/auth/sign-in?redirect=
Protected routes
Route protection is configured in src/middleware.ts. The middleware usesauth.getSession() from the Neon Auth server client:
import { auth } from "@/lib/auth/neon-server";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const AUTH_REQUIRED_PREFIXES = ["/profile", "/saved", "/liked"];
const ADMIN_PREFIXES = ["/admin"];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
const isAuthRoute = AUTH_REQUIRED_PREFIXES.some((p) => pathname.startsWith(p));
const isAdminRoute = ADMIN_PREFIXES.some((p) => pathname.startsWith(p));
if (!isAuthRoute && !isAdminRoute) return NextResponse.next();
const { data: session } = await auth.getSession();
if (!session) {
const signInUrl = new URL("/auth/sign-in", request.url);
signInUrl.searchParams.set("redirect", pathname);
return NextResponse.redirect(signInUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/profile/:path*", "/saved/:path*", "/liked/:path*", "/admin/:path*"],
};Session management
Sessions are managed automatically by Neon Auth using signed cookies. The NEON_AUTH_COOKIE_SECRET must be a strong random string. Session duration is controlled by Neon Auth's configuration.
User management
Users are stored in the User table in your Neon Postgres database. To grant admin access, update the role field to ADMIN using Prisma Studio (npm run db:studio). The Neon Auth dashboard also lets you view active sessions and manage sign-in providers.