← Back to all articles
•5 min read

Enforcing Dual AWS Cognito User Pools with Next.js Edge Middleware

Route isolation and token validation under 8ms at the edge for hospital recruiters and jobseeking healthcare practitioners sharing a single domain.

AWS CognitoEdge MiddlewareNext.jsJWTSecurity

The Problem: Cross-Role Session Collision

MedLinkJobs operates with two fundamentally distinct user pools: DoctorsPool (candidates searching and applying for healthcare jobs) and HospitalPool (recruitment teams posting jobs and managing applicants).

Both portals share the same top-level domain for branding and SEO authority. Initially, client-side route guards checked authentication state after the page component had already mounted. This caused visible UI flashing: an unauthenticated user would see a glimpse of the protected recruiter dashboard before being redirected.

Even worse, a doctor authenticated under the DoctorsPool navigating to a recruiter dashboard route (/recruiter/pipeline) would cause client-side GraphQL errors because their token was valid for Cognito, but invalid for hospital operations.

Edge middleware classifying route domains and verifying pool claimstypescript
// Edge middleware in Next.js
export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const token = extractCognitoToken(request.cookies);

  if (isRecruiterRoute(pathname)) {
    if (!token) {
      return NextResponse.redirect(new URL('/login?role=recruiter', request.url));
    }
    const claims = decodeJwt(token);
    // Enforce that token was issued by the HospitalPool, not DoctorsPool
    if (claims.iss !== process.env.HOSPITAL_POOL_ISSUER) {
      return NextResponse.redirect(new URL('/unauthorized', request.url));
    }
  }

  return NextResponse.next();
}

The Fix: Zero-Latency Edge Route Classification

We moved the entire authentication verification pipeline into Next.js Edge Middleware. Before any React components or layout bundles are dispatched, the edge runtime inspects the request cookie headers.

The middleware classifies the path into public, jobseeker, or recruiter domains, extracts the Cognito access token, and decodes the JWT claims in <8ms.

If a user attempts to cross boundaries or their session has expired, the edge runtime immediately responds with an HTTP 307 temporary redirect to the appropriate login portal. Zero protected HTML is ever sent to unauthorized clients.

Security and User Experience Benefits

1. Elimination of client-side flash of unauthenticated content (FOUC).

2. Complete cryptographic boundary between healthcare practitioners and hospital recruiters.

3. Single-session enforcement ensuring recruiter accounts cannot be concurrently accessed from unauthorized devices.

PK
Pushyamithra Kasthuri
Front-End Web Developer · Hyderabad, India
Portfolio navigation

Find a flow or action

Search all twelve flows, sections, and display settings.