Authentication Setup with Neon Auth

How to configure Neon Auth for user authentication in BloggFast.

Last updated:

Enable Neon Auth

  1. Open your Neon project dashboard at neon.tech
  2. Click Auth in the left sidebar of your project
  3. Click Enable Auth
  4. Neon Auth will provision the required auth tables and configuration automatically

Copy environment variables

Once Neon Auth is enabled, the dashboard will show two environment variables. Copy these to your .env.local:

.env.local
NEON_AUTH_BASE_URL="https://ep-xxx.neonauth.region.aws.neon.tech/neondb/auth"
NEON_AUTH_COOKIE_SECRET="your-cookie-secret-from-neon"

Warning

The NEON_AUTH_COOKIE_SECRET is used to sign session cookies. Treat it like a password — never expose it, and use a strong random string in production. Generate one with: openssl rand -base64 32

How auth works in BloggFast

BloggFast uses @neondatabase/auth for server-side session management. Here's the flow:

  1. User visits /auth/sign-in or /auth/sign-up
  2. The auth form submits credentials to Neon Auth's API via a Server Action in /api/auth/
  3. On success, Neon Auth sets a signed session cookie
  4. The middleware reads this cookie on every request to protected routes
  5. Invalid or missing sessions redirect to /auth/sign-in

The server-side auth client is initialized in src/lib/auth/neon-server.ts:

src/lib/auth/neon-server.ts
import "server-only";
import { createNeonAuth } from "@neondatabase/auth/next/server";

export const auth = createNeonAuth({
  baseUrl: process.env.NEON_AUTH_BASE_URL!,
  cookies: {
    secret: process.env.NEON_AUTH_COOKIE_SECRET!,
  },
});

Protected routes

Route protection is handled by src/middleware.ts. The following routes require authentication:

Route prefixProtection
/admin/*Requires authentication — redirects to sign-in if session missing
/profile/*Requires authentication — redirects to sign-in if session missing
/saved/*Requires authentication — redirects to sign-in if session missing
/liked/*Requires authentication — redirects to sign-in if session missing

The redirect target is /auth/sign-in?redirect= with the original URL appended.

Neon Auth's own API routes at /api/auth/* are always whitelisted by the middleware.

Role-based access control

Users have a role field in the User model with three possible values defined in the UserRole enum:

typescript
enum UserRole {
  USER    // Standard reader account
  EDITOR  // Can create and edit articles
  ADMIN   // Full access to all admin features
}

The default role for new sign-ups is USER. To grant admin access to an account, update the user's role directly via Prisma Studio (npm run db:studio) or the Neon console.

Note

The current middleware only checks for a valid session — it does not enforce the ADMIN role at the middleware level. Role enforcement is done within individual admin server actions and API routes. You can extend the middleware to add role-based gating if needed.