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.
CleanShot_2025-08-25_at_14.13.362x.png
Was this page helpful?