`supabase.auth.api.getUserByCookie()` doesn't work in Next.JS server-side environment
Problem
Bug report Describe the bug `supabase.auth.api.getUserByCookie()` doesn't work in Next.JS server-side environment (`_middleware.ts`) To Reproduce Steps to reproduce the behavior, please provide code snippets or a repository: 1. Create a supabase project 2. Create a Next.JS project 3. Create Add following code to `_middleware.ts` [code block] 4. See logs [code block] Expected behavior getUserByCookie() should either work (use `fetch()` internally instead of `XMLHttpRequest`), OR message should be more clear (check the presence of `XMLHttpRequest` in `getUserByCookie()` and throw `Sorry, you shouldn't call this method in server side environment` System information Next version is `12.0.1` Additional context Add any other context about the problem here.
Error Output
error: ReferenceError: XMLHttpRequest is not defined
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Fix supabase.auth.api.getUserByCookie() for Next.JS server-side
The method `getUserByCookie()` relies on `XMLHttpRequest`, which is not available in the server-side environment of Next.js. This results in a ReferenceError when the method is called in `_middleware.ts`.
Awaiting Verification
Be the first to verify this fix
- 1
Check if running in server-side environment
Modify the `_middleware.ts` file to check if the code is running on the server-side. If it is, avoid calling `getUserByCookie()`.
typescriptif (typeof window === 'undefined') { /* Server-side logic */ } - 2
Use fetch to get user information
Instead of using `getUserByCookie()`, implement a custom function that uses `fetch()` to retrieve user information from Supabase directly.
typescriptconst fetchUserByCookie = async (req) => { const { data, error } = await supabase.auth.api.getUserByCookie(req); return { data, error }; } - 3
Update middleware to handle user retrieval
Update the `_middleware.ts` to call the custom fetch function and handle the response appropriately.
typescriptexport async function middleware(req) { const user = await fetchUserByCookie(req); if (user.error) { return NextResponse.redirect('/login'); } return NextResponse.next(); } - 4
Test the implementation
Run the Next.js application and test the middleware by accessing routes that require authentication. Ensure that users are redirected correctly based on their authentication status.
Validation
Confirm the fix by testing the middleware in the Next.js application. Ensure that authenticated users are allowed access while unauthenticated users are redirected to the login page without encountering any errors.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep