Clerk handshake causes slow initial load for NextJS standalone deployment
My NextJS app is deployed as a standalone build on AWS (ECS) - so my middleware is running in the same place as my app. This means that for Clerk to complete a handshake multiple round trips need to be converted before the first byte is downloaded.
I was thinking about solving this by either: A) Adding a viewer request function to handle clerk handshakes, or B) Figuring out how to handle the token refresh entirely on the backend.
Anyone else ever run into this issue?
Attached pics are my very rough understanding of how clerk handshakes work, so please correct me if I'm wrong 🙂




1 Reply
Solved: Implemented the initial redirect in a cloudfront viewer request function by doing the following:
1. Check the request uri path to make sure it's an initial request to a dynamic page. Don't do the redirect for static assets (e.g., next_), api routes, if query params from clerk exist, or if the
__clerk_redirect_count
cookie exists.
2. Parse the __session cookie.
3. If the cookie is expired (exp
), then return a 307 to redirect to https://{session.iss}/v1/client/handshake?redirect_url={encoded_request_url}&suffixed_cookies=true
. Set the cache-control
header to no-store
.
Note: this approach seems to only work on the Clerk production instance, not development (in dev I always end up signed out after this flow). The diagrams I have above are for development - in production that final redirect does not happen.