AWS Builder Center

Why your JWT Cookie Dies Between Vercel and EC2 (And How I Fixed It)

A raw EC2 instance gives you no managed domain and no HTTPS by default - here's the auth bug that cost me, three rounds of fixes, and the one gap that's still open.

I'm Nishit, a third-year Computer Science undergrad at RV University Bengaluru, and I lead our AWS Student Builder Group. DevPulse started as a side project to fix something I kept running into on my own team projects: nobody could tell who was actually blocked on what until standup, by which point the PR had already been stale for two days. This is the story of the ugliest bug in it, and the two times I thought I'd fixed it before I actually had.



The setup

DevPulse's backend is FastAPI running on an AWS EC2 t3.micro instance, managed by systemd. The frontend is Next.js 15, deployed on Vercel's edge network. Two completely different origins, two completely different infrastructure models, and I needed a single authenticated session to survive across both.
Browser and GitHub OAuth on the outside, Vercel and EC2 exchanging auth tokens and API calls in the middle, Groq and Slack as downstream services

I chose EC2 over Lambda for the backend specifically because APScheduler needs a long-running process for hourly GitHub sync jobs, and that doesn't map cleanly onto stateless function invocations. Vercel handles the frontend because Next.js edge middleware and static assets are what it's built for. Reasonable split. What I underestimated was what that split costs you: unlike Lambda behind API Gateway or ECS/Fargate behind an ALB, a raw EC2 instance gives you no managed domain and no HTTPS by default. You own both yourself, or you don't have them. That gap is the actual root cause of everything below.



The problem, in one sentence

A cookie set by  your-ec2-ip:8000  does not belong to  devpulse-nish.vercel.app , and the browser will not pretend otherwise.

Attempts 1 and 2: cookies that were never going anywhere

First working version of session auth ( 0cf4b86 ) hardcoded  secure=False  with no  domain  parameter at all. It passed local testing because  localhost:3000  and  localhost:8000  behave like the same effective origin for cookies in most dev setups: a false positive that hid the real problem.
The next pass ( ad34179 ) added environment awareness:
-secure=False,
+secure=is_prod,
+domain=os.getenv("COOKIE_DOMAIN") if is_prod else None,

Looked like a fix. Wasn't. The redirect target was still just  {FRONTEND_URL}/dashboard/{username} , no token attached, and  COOKIE_DOMAIN  was never documented in the env template, so in practice it was unset anyway. Here's the actual failure sequence this produced:
  1. User completes GitHub OAuth at  http://your-ec2-ip:8000/auth/callback 
  1. Backend calls  set_cookie() , cookie is scoped to the EC2 origin
  1. Backend redirects the browser to  https://devpulse-nish.vercel.app/dashboard/... 
  1. The browser loads the Vercel page. It never sends the EC2-scoped cookie there: different origin, full stop
  1. Frontend fetches  http://your-ec2-ip:8000/pr/bottlenecks  with no cookie attached
  1.  get_authenticated_user  throws  401 
  1. Dashboard renders empty, or redirect-loops back to  / 
 COOKIE_DOMAIN  was never actually documented in the README's env template, so in practice it likely wasn't set, meaning  domain=None  and the cookie stayed scoped to a raw IP that no other origin could ever match anyway.

Attempt 3: a live network call at the edge (and why I killed it)

Before landing on the fix, I tried solving this at the Next.js middleware layer by having it call the backend directly to verify the session on every request ( a2581f9 , later named  proxy.ts ). The core of it:
const res = await fetch(`${BACKEND_URL}/auth/me`, {
headers: { Cookie: `devpulse_session=${sessionCookie}` },
});
if (!res.ok) return NextResponse.redirect(new URL("/", request.url));

Technically works. But it adds a network round-trip to EC2 on every protected route hit at the edge: latency you eat on every page load, and a new failure mode if EC2 has a bad moment. It also didn't fix the root cause. The cookie still had to somehow get from EC2's origin onto Vercel in the first place. I deleted this file the same day I landed the real fix.



The actual fix: relay the token through the URL once

redirect_url = f"{FRONTEND_URL}/dashboard/{db_user.username}?token={session_token}"

One line. Instead of relying on the browser to carry a cross-origin cookie, the backend hands the JWT to the frontend explicitly, via the redirect URL, exactly once. Next.js middleware then intercepts it and sets its own cookie, scoped to its own origin:
export function middleware(request: NextRequest) {
const { pathname, searchParams } = request.nextUrl;
const token = searchParams.get("token");

if (token) {
const url = request.nextUrl.clone();
url.searchParams.delete("token");
const response = NextResponse.redirect(url);
response.cookies.set("devpulse_session", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 7 * 24 * 60 * 60,
});
return response;
}

if (pathname.startsWith("/dashboard")) {
const sessionCookie = request.cookies.get("devpulse_session")?.value;
if (!sessionCookie) return NextResponse.redirect(new URL("/", request.url));
}

return NextResponse.next();
}

The token is stripped from the URL in the same response that sets the cookie, so it doesn't linger in the visible address bar after the redirect completes.
One CORS fix had to land alongside this ( a2581f9 ): the Vercel origin wasn't in the backend's allow-list before that commit.
app.add_middleware(
CORSMiddleware,
allow_origins=[os.getenv("FRONTEND_URL", "http://localhost:3000"), "http://127.0.0.1:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

Meaning even a correctly-scoped cookie would have hit a  403  on preflight before ever reaching the endpoint.



The URL-relay fix wasn't the end of it

Shipping the  ?token=  relay felt done. It wasn't. Sitting with it a bit longer, three things were still wrong, all in the same auth path:
  1. The value in that URL was the actual 7-day session JWT. Short-lived exposure is still exposure. It was still landing in EC2 access logs, Vercel request logs, browser history, and GitHub's OAuth redirect logging, fully valid for a week if anyone ever pulled it from any of those places.
  1. The backend was still calling  set_cookie()  on the EC2 origin inside  /auth/callback , a cookie the browser would drop on the next cross-origin redirect regardless. Dead code that looked like a security control and wasn't one.
  1.  middleware.ts  was setting the real session cookie from a value that had already been sitting in a URL. By the time the cookie was set, the token had already made every stop on the "logged forever" tour above.
The actual fix, landed in  160c594 :
  •  /auth/callback  now issues a relay token, 2-minute expiry, a  "type": "relay"  claim that's checked and rejected if anyone tries to use it as a real session credential, instead of the session JWT itself.
  • The dead  set_cookie()  call on the EC2 origin is gone.
  • A new server-side Next.js route,  /api/auth/exchange , does the real work: it calls the backend privately (server-to-server, never visible to the browser), the backend validates the relay token and returns the actual session JWT via a  Set-Cookie  response header, and that header gets forwarded onto the Vercel-origin response before redirecting to the dashboard.
Browser → EC2/auth/login → GitHub → EC2/auth/callback
→ Vercel/api/auth/exchange?relay=<2min-token>&next=/dashboard/...
→ (server-side) EC2/auth/exchange validates relay token
→ returns Set-Cookie: devpulse_session=<7-day-jwt>; httpOnly
→ Browser receives cookie on vercel.app origin, redirect to dashboard ✓

The session JWT itself never touches a URL, a browser history entry, or a client-visible log line again. Only a 2-minute, type-checked, disposable token does, and only briefly.
__________________________________________________________________________________________

Sitting with it longer surfaced two more gaps

Two questions I asked myself after  160c594  shipped, and didn't like my own answers to:
1) Is the relay token replayable? Type-check and 2-minute expiry aren't the same as single-use. Nothing stopped the same relay token, if captured from an EC2 access log fast enough, from being replayed a second time inside that window. Fixed by adding a  jti  (a UUID, unique per token) to every relay token, and having  /auth/exchange  keep an in-memory record of which  jti s have already been redeemed, rejecting on any repeat. Correct for the current single-process deployment; a multi-instance setup would need that store moved to Redis or a short-TTL DB table instead of process memory.
2) Can anyone who gets hold of a relay token call  /auth/exchange  directly? Yes, previously. Closed with a pre-shared  X-Exchange-Secret  header that the endpoint requires and only the Next.js server route (never the browser) knows. It's a plain env var with no  NEXT_PUBLIC_  prefix, so it's invisible client-side.
Both landed in  9671571 . Neither is a TLS substitute, and I'm not presenting them as one.
__________________________________________________________________________________________

What this still doesn't fix

One gap left, and it's the one that actually matters most:
  • The Vercel to EC2 exchange call still isn't on TLS. The  Set-Cookie: devpulse_session=<7-day-jwt>  response from  /auth/exchange  still crosses the public internet in plaintext. The  X-Exchange-Secret  header stops arbitrary callers from reaching the endpoint at all, but it does not encrypt what goes over the wire once a legitimate call is made. A MITM on the path between Vercel's infra and my EC2 instance can still capture that cookie. TLS (ALB + ACM, or Nginx + Let's Encrypt) is infrastructure work, not code, and it's the only complete fix for this.
  • SQLite + in-process APScheduler. Fine at current scale, but it's a wall: horizontal scaling means a real migration to Postgres and a proper job queue.
  • No CI/CD. Deploys are still manual SSH and systemd restarts.
  • No observability. Logging is  logging.basicConfig(level=logging.INFO)  to stdout, captured only by the systemd journal on the instance itself. If this bug happens again, I have no structured trace to find it faster than I did this time.
__________________________________________________________________________________________

Results

  • 22 backend pytest tests passing (auth/session contract, bottleneck engine logic, Fernet token-encryption roundtrip at the DB layer)
  • Rate limits holding at 10/min (standup, Slack push, NL query) and 30/min (bottleneck reads) with no auth-adjacent regressions across any of the three commits
  • Zero redirect-loop reports since  ac955c8 
  • As of  9671571 : no long-lived session JWT in any browser-visible surface, relay tokens are single-use and endpoint-gated. Three independent checks ( type == "relay" , expiry, unused  jti ) all have to pass before a session is ever issued.



What I'd do differently

Put TLS in front of this from day one: ALB and ACM certificate, or at minimum Nginx with Let's Encrypt, instead of layering three rounds of application-level fixes on top of a transport layer that was insecure the entire time. Every one of those three commits made the system meaningfully better, but none of them could fully close the gap, because the gap was never in the code to begin with. That's the actual lesson here: know which layer your vulnerability lives in before you start fixing it. TLS is next, before Postgres, before CI/CD. __________________________________________________________________________________________
DevPulse is live at  devpulse-nish.vercel.app . Code on  GitHub . I'd genuinely like to hear how others have handled auth across a split EC2/Vercel (or similar multi-provider) deployment: drop it in the comments.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article