How to mock better-auth with MSW?
I tried to use MSW to mock the (GitHub) OAuth flow. However, I have been unsuccessful in getting the session on the server.
Here is a minimal reproduction:
https://codesandbox.io/p/devbox/better-auth-with-msw-5dy86g
Please test on a new browser tab:
https://5dy86g-3000.csb.app/
Steps to reproduce:
1. Run the server
MOCK_SERVER=true pnpm dev
(if the server is running at first, please restart it with this command)
2. Go to https://5dy86g-3000.csb.app/
3. Click "Sign In"
4. Copy the state
in the URL. E.g., &state=XXX
, copy the XXX
5. Go to https://5dy86g-3000.csb.app/api/auth/callback/github?code=mock_github_code&state=XXX directly, paste your state at the end
6. OAuth flow is done.
Notes:
- If you're getting an invalid_code
error, please try to fork the codesandbox and test with your own csb terminal.
- instrumentation.ts
only runs when pnpm dev
, if any changes are made in instrumentation.ts
, please restart the next-server.
4 Replies
Found out that MSW made
await headers()
become a nested headers:
Still finding the solution.
Not sure if the above is correct. Passing (await headers()).headers
will make it work when MSW is running.
Also found out that headers becomes empty after new Headers()
in toAuthEndpoints()
https://github.com/better-auth/better-auth/blob/557dc39c32ca639a3b221d93250eb4b828120378/packages/better-auth/src/api/to-auth-endpoints.ts#L55
Seems that only happen in Better AuthNo MSW:

With MSW:

---
This is not related to Better Auth. I will try to find the solution in MSW.
May be use MSW alternatives