ssr: Error: Invalid UTF-8 sequence crashing Vercel

Bug report

  • [x ] I confirm this is a bug with Supabase, not with my own application.
  • [ x] I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

On version "@supabase/ssr": "^0.4.0",

image Randomly been getting these errors for my app. Only solution is to destroy my cookies and refresh.

Error: Invalid UTF-8 sequence at (node_modules/@supabase/ssr/dist/module/utils/base64url.js:187:0) at (node_modules/@supabase/ssr/dist/module/utils/base64url.js:90:0) at (node_modules/@supabase/ssr/dist/module/cookies.js:246:30) at (node_modules/@supabase/auth-js/dist/module/lib/helpers.jsđź’Ż0) at (node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:787:0) at (node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:768:0) at (node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:714:0)

This us a super weird bug where when I visit my website it just literally crashes. However clearing my cookies the website works for a bit then stops.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

I do not know how the bug occurs.

Screenshots

If applicable, add screenshots to help explain your problem.

System information

Running on a nextjs app with supabase. My app allows google logins

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 39 (9 by maintainers)

Most upvoted comments

Solution: Progressive Token Fragment Parsing to Fix Invalid UTF-8 Sequence

I found the root cause and implemented a working solution for this UTF-8 sequence error.

Root Cause Analysis

The issue occurs when Supabase authentication tokens are split into multiple cookie chunks, but not all chunks are necessary for the current session. In my case:

  • Expected: 2 cookie chunks for current session
  • Actual: 3 cookie chunks exist in browser
  • Problem: Supabase tries to combine all 3 chunks, causing base64 decoding failure

How to Reproduce

You can reproduce this issue by manually creating extra cookie chunks:

  1. Check your current sb-*-auth-token.0, sb-*-auth-token.1 cookies
  2. Create a fake sb-*-auth-token.2 cookie with random base64 content
  3. Refresh the page - you’ll get the UTF-8 sequence error

Solution: Progressive Token Fragment Parsing

I implemented a middleware solution that progressively parses token fragments until a valid token is found, then discards unnecessary fragments.

Core Logic

// Progressive token fragment parsing function
function optimizeTokenFragments(cookies: Array<{ name: string, value: string }>) {
    // Find all Supabase auth-token fragments
    const authTokenPattern = /sb-.*-auth-token\.(\d+)$/;
    const authTokenCookies = cookies.filter(cookie => authTokenPattern.test(cookie.name));
    
    if (authTokenCookies.length === 0) return cookies;

    // Sort fragments by number
    authTokenCookies.sort((a, b) => {
        const aIndex = parseInt(a.name.match(authTokenPattern)[1]);
        const bIndex = parseInt(b.name.match(authTokenPattern)[1]);
        return aIndex - bIndex;
    });

    // Progressive parsing: try 1 fragment, then 2, then 3...
    let validFragments = [];
    let combinedValue = '';

    for (let i = 0; i < authTokenCookies.length; i++) {
        const fragment = authTokenCookies[i];
        
        // Remove base64- prefix and combine
        const fragmentValue = fragment.value.startsWith('base64-') 
            ? fragment.value.substring(7) 
            : fragment.value;
        
        combinedValue += fragmentValue;

        try {
            // Try to decode and parse
            const decoded = atob(combinedValue);
            const parsed = JSON.parse(decoded);
            
            // Check if token is valid (has access_token and user)
            if (parsed.access_token && parsed.user) {
                validFragments = authTokenCookies.slice(0, i + 1);
                break; // Stop here - we found the minimum required fragments
            }
        } catch (error) {
            // Continue to next fragment
        }
    }

    // Return optimized cookies with only necessary fragments
    if (validFragments.length > 0 && validFragments.length < authTokenCookies.length) {
        const validNames = new Set(validFragments.map(f => f.name));
        return cookies.filter(cookie => {
            if (authTokenPattern.test(cookie.name)) {
                return validNames.has(cookie.name);
            }
            return true;
        });
    }

    return cookies;
}

Implementation in Middleware

// In your Supabase middleware
const supabase = createServerClient(url, key, {
    cookies: {
        getAll() {
            const rawCookies = request.cookies.getAll();
            // Apply optimization before returning to Supabase
            return optimizeTokenFragments(rawCookies);
        },
        setAll(cookiesToSet) {
            // Standard setAll implementation
        }
    }
});

// Also handle UTF-8 errors gracefully
let user;
try {
    user = await supabase.auth.getUser();
} catch (authError) {
    if (authError.message?.includes('UTF-8')) {
        // Treat as logged out user instead of crashing
        user = { data: { user: null }, error: null };
    } else {
        throw authError;
    }
}

Additional Cleanup (Optional)

You can also delete the unnecessary cookie fragments from the client:

// After identifying invalid fragments, delete them from client
const invalidFragments = ['sb-xxx-auth-token.2', 'sb-xxx-auth-token.3'];
invalidFragments.forEach(fragmentName => {
    response.cookies.set(fragmentName, '', {
        path: '/',
        maxAge: 0,
        httpOnly: true,
        secure: true,
        sameSite: 'lax'
    });
});

Results

  • No more UTF-8 sequence errors
  • Reduced network payload (fewer cookie fragments)
  • Graceful degradation when errors occur
  • No impact on normal authentication flow

This solution has been running in production for several weeks without issues.

Testing

To test this fix:

  1. Implement the progressive parsing logic
  2. Set DEBUG='middleware:cookie' to see optimization logs
  3. Verify that unnecessary cookie fragments are identified and handled
  4. Test login/logout flows to ensure normal operation

Hope this helps others experiencing the same issue!

Maybe I’m missing something, but it’s kind of insane. Any error shouldn’t crash the whole app for the user, instead it should show some feedback. But for some reason I cannot handle this error…

I did find a mechanism in the cookie-chunking logic, to where it’s possible to have a “middle” cookie size of less than the typical 3216. After the whole value is encoded with encodeURIComponent(), it tries to make sure it’s not splitting a character escape sequence between cookie chunks.

All of that to say it’s possible to have a couple of cookie sizes that could’ve been rolled into one cookie, but they were trying to do the above, so the content got split. If that makes sense.

Our users are facing this too - and it’s pretty debilitating as it happens very often

We’re having the same issue:

In our case, the auth cookie is split into 3 parts: token.0, token.1 and token.2.

The combination of

  • token.0 + token.1 is valid base64 âś…
  • token.0 + token.2 is valid base64 âś…
  • token.0 + token.1 + token.2 is invalid ❌

token.0 and token.2 have the same cookie expiry date, so apparently the have been created at the same time, token.1 has a different expiry date which is dated after the other two tokens.

image

Maybe Supabase detects that the first part can stay unchanged, only sets the second (.1) part and “forgets” to unset the third (.2) part?

Hi @fincha, thanks for your insight! I notice the same thing that deleting all cookies resolves the issue; however only temporarily. This issue always comes back after the session times out (3600 seconds) and the user is on a page that checks supabase.auth.getUser()

I am not modifying the cookies/JWT via hooks or anything else. I also added the “cookieEncoding”: “raw” prop, too. I already updated the codebase so I don’t want to face any regressions by downgrading to @supabase/ssr": "^0.0.10 as suggested by @Nishchit14.

Anyone else found a solution to this? If it applies I am authenticating through Azure but have not been able to resolve from that end.

Thanks! 👾🚀

Trying and will get back to you (Apologies, accidentally closed the task. reopened it now)

@k2xl @supabase/ssr": "^0.0.10