Use MSW to Mock Authentication in Remix

Share this video with your friends

Send Tweet

Mocking authentication comes down to how it's implemented. With Mock Service Worker, you can mock the "Set-Cookie" response header to emulate a user session, but with Remix you don't even have to. Instead, in this lesson we will intercept only the authorization call to a database, leaving Remix to handle sessions, cookies, and auth state for us.

~ 8 months ago

This part doesn't work for me, even in the "completed" branch. I get this error:

Application Error

TypeError: Secret key must be provided. at Object.exports.sign (/Users/valla/Projects/msw-movie-app/node_modules/cookie-signature/index.js:18:29) at sign (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/node/dist/crypto.js:22:46) at encodeCookieValue (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/server-runtime/dist/cookies.js:85:21) at Object.serialize (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/server-runtime/dist/cookies.js:67:63) at commitSession (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/server-runtime/dist/sessions/cookieStorage.js:39:43) at action2 (/Users/valla/Projects/msw-movie-app/app/routes/_grid.sign-in.tsx:53:27) at processTicksAndRejections (node:internal/process/task_queues:95:5) at Object.callRouteActionRR (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/server-runtime/dist/data.js:35:16) at callLoaderOrAction (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/router/router.ts:3688:16) at submit (/Users/valla/Projects/msw-movie-app/node_modules/@remix-run/router/router.ts:2833:16)

~ 8 months ago

Same error for me!

Artem Zakharchenko
Artem Zakharchenko(instructor)
~ 8 months ago

Hi, folks! Thanks for pointing that out.

The error was caused by Remix missing the value in the "secrets" key in "app/session.ts" to sign the authentication cookie. That secret was loaded from the ".env" file, which is normally ignored in Git, so you didn't have it and got the error because it was missing.

For the sake of the exercises, I've committed the ".env" file to Git so if you rebase the repo now, you will get a dummy secret value and the error will be gone. Please note that in real applications, you MUST NEVER commit ".env" files to Git.