iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔐

Practical Insights into Designing a Supabase Auth Flow for Next.js and Expo

に公開

Introduction

In the diary app "Storyie," I have implemented authentication using Supabase Auth for both Web (Next.js) and Mobile (Expo).

While "Supabase Auth makes authentication easy" is a common sentiment, there are surprisingly many aspects to consider when supporting both Web and Mobile, and ensuring everything works correctly across Next.js Server Components, Server Actions, and Middleware.

In this article, I will share the design decisions and insights I gained from my actual experience with this individual development project.

Overall Architecture

The authentication for Storyie is structured as follows:

  • Web (Next.js): Google / Apple OAuth → Server Action → Callback Route Handler
  • Mobile (Expo): Google / Apple Native SDKs → signInWithIdToken → SecureStore
  • API Routes: Supports both Cookie-based (Web) and Bearer token (Mobile) authentication
  • Middleware (proxy.ts): Session refresh + Route protection
[Web Browser]
  └─ Server Action (signInWithOAuth)
       └─ Supabase OAuth redirect
            └─ /api/auth/callback (Code exchange + Cookie setting)

[Expo App]
  └─ GoogleSignin / AppleAuthentication (Native SDK)
       └─ supabase.auth.signInWithIdToken
            └─ Save to SecureStore

Web Design: Three-Layer Supabase Client

To handle Supabase Auth correctly in Next.js, the way the client is created must vary depending on the use case.

1. For Server Components (Read-Only)

// Share the instance within the same request using React.cache()
export const createReadOnlyServerClient = cache(async () => {
  const cookieStore = await cookies();
  return createServerClient({
    cookies: {
      getAll: () => cookieStore.getAll(),
      setAll: () => {}, // Do nothing as it is read-only
    },
  });
});

Since Server Components cannot write cookies, setAll is left empty. This is an intentional design; even if Supabase's internal onAuthStateChange attempts to write cookies asynchronously, it will be skipped safely.

2. For Server Actions / Route Handlers (Read/Write)

export async function createClient() {
  const cookieStore = await cookies();
  return createServerClient({
    cookies: {
      getAll: () => cookieStore.getAll(),
      setAll: (cookiesToSet) => {
        try {
          for (const { name, value, options } of cookiesToSet) {
            cookieStore.set(name, value, options);
          }
        } catch {
          // Ignore calls from outside the request context
        }
      },
    },
  });
}

The key here is including a try-catch block within setAll. Supabase's GoTrueClient calls _notifyAllSubscribers internally in an asynchronous manner, which can occasionally lead to errors when attempting to write cookies after the request context has ended.

3. For Browser (Singleton)

const globalForSupabase = globalThis as unknown as {
  supabaseInstance: TypedSupabaseClient | undefined;
};

export function createClientSupabase(): TypedSupabaseClient {
  if (!globalForSupabase.supabaseInstance) {
    globalForSupabase.supabaseInstance = createBrowserClient<Database>(
      env.NEXT_PUBLIC_SUPABASE_URL,
      env.NEXT_PUBLIC_SUPABASE_ANON_KEY
    );
  }
  return globalForSupabase.supabaseInstance;
}

On the browser side, I manage a singleton using globalThis. This prevents warnings that occur when multiple GoTrueClient instances are created. It also ensures that instances are not duplicated when modules are reloaded due to Next.js HMR (Hot Module Replacement).

Lessons Learned from OAuth Callbacks

In the OAuth callback Route Handler, I had to address the issue where Supabase attempts to set cookies from an asynchronous callback.

const cookiesToSet: CookieToSet[] = [];

const supabase = createServerClient({
  cookies: {
    getAll: () => request.cookies.getAll(),
    setAll: (cookies) => {
      // Buffer and set to NextResponse collectively at the end
      for (const cookie of cookies) {
        const existingIndex = cookiesToSet.findIndex(c => c.name === cookie.name);
        if (existingIndex >= 0) {
          cookiesToSet[existingIndex] = cookie;
        } else {
          cookiesToSet.push(cookie);
        }
      }
    },
  },
});

Since setAll might be called multiple times, I buffer the cookies while overwriting those with the same name, then apply them all to the final NextResponse.

Determining First-Time Login

To display a welcome message the first time a user logs in to the Web version, I determine it based on the difference between created_at and last_sign_in_at.

const createdAt = new Date(data.user.created_at).getTime();
const lastSignIn = new Date(data.user.last_sign_in_at).getTime();
const isFirstLogin = Math.abs(lastSignIn - createdAt) < 60000; // Within 1 minute

It is not perfect, but it was sufficiently practical for the scale of an individual development project.

Session Refresh Strategy in Middleware

In the Middleware (proxy.ts), I employ different strategies for public and protected routes.

if (isPublicRoute(pathname)) {
  // getSession(): Local token refresh (no network required)
  const { supabaseResponse } = await refreshSessionOnly(req);
  return supabaseResponse;
}

// Protected route: Server-side validation of JWT via getUser() (secure)
const { supabaseResponse, user } = await createClientAndRefreshSession(req);
if (!user) {
  return createLoginRedirect(req, pathname);
}
  • Public Routes: Local refresh only via getSession() (no round-trip to the Auth server).
  • Protected Routes: JWT validation against the Auth server via getUser() (to prevent cookie spoofing).

This ensures performance on public pages while maintaining security on protected ones.

Mobile Design: Native SDK + signInWithIdToken

On the Expo side, I obtain tokens using Google / Apple native SDKs and authenticate using Supabase's signInWithIdToken.

// Google
const userInfo = await GoogleSignin.signIn();
const { data, error } = await supabase.auth.signInWithIdToken({
  provider: "google",
  token: userInfo.data.idToken,
});

// Apple
const credential = await AppleAuthentication.signInAsync({ /* ... */ });
const { data, error } = await supabase.auth.signInWithIdToken({
  provider: "apple",
  token: credential.identityToken,
});

Unlike the Web OAuth flow (browser redirect), mobile authentication completes without redirection because the native SDK returns the ID token directly.

Session Persistence with SecureStore

In the mobile app, I store session information in expo-secure-store, separately from the Supabase session.

async function saveSessionToSecureStore(session: Session) {
  await SecureStore.setItemAsync(USER_SESSION_KEY, JSON.stringify(session.user));
  await SecureStore.setItemAsync(TOKEN_KEY, session.token);
}

Upon startup, I check SecureStore first; if not found, I fetch from Supabase. This allows displaying user information even when offline, improving perceived speed. Additionally, I monitor the TOKEN_REFRESHED event in onAuthStateChange to automatically update tokens in SecureStore.

Dual Authentication for API Routes

To create API routes that support both Web (Cookies) and Mobile (Bearer tokens), I prepared an authentication helper.

export async function authenticateApiRequest(request: NextRequest) {
  const supabase = await createClient();

  // Prioritize Bearer token (Mobile)
  const bearerToken = extractBearerToken(request);
  if (bearerToken) {
    const { data, error } = await supabase.auth.getUser(bearerToken);
    return { user: data.user, error };
  }

  // Fallback to cookie-based (Web)
  const { data, error } = await supabase.auth.getUser();
  return { user: data.user, error };
}

Prioritizing the Bearer token ensures smooth API calls from the mobile app.

The "Too Many getUser() Calls" Issue on the Client Side

I noticed during development that multiple client components were calling getUser() individually, resulting in over four Auth API requests per second.

As a solution, I implemented a 30-second cache with request deduplication.

let pendingRequest: Promise<User | null> | null = null;
let cachedUser: User | null = null;
let cacheTimestamp = 0;

export async function getCachedUser(): Promise<User | null> {
  // Return if cache is valid
  if (cachedUser && Date.now() - cacheTimestamp < 30_000) {
    return cachedUser;
  }
  // Wait for ongoing request (deduplication)
  if (pendingRequest) return pendingRequest;

  pendingRequest = (async () => {
    try {
      const supabase = createClientSupabase();
      const { data } = await supabase.auth.getUser();
      cachedUser = data.user;
      cacheTimestamp = Date.now();
      return data.user;
    } finally {
      pendingRequest = null;
    }
  })();
  return pendingRequest;
}

Furthermore, I combined tab visibility changes and periodic checks (10-minute intervals) in a SessionRefreshProvider to ensure sessions do not expire even if left open for a long time.

Transferring Sessions from Mobile to Web

When implementing a "View on Web" feature in the mobile app, I created a /api/auth/mobile-transfer endpoint to transfer the mobile access token to a Web session.

The flow is as follows:

  1. The mobile app opens the Web URL with the access token as a query parameter.
  2. The Route Handler validates the token and establishes a Web-side session using setSession.
  3. Cookies are set, and the user is redirected.

It is not a perfect mechanism (e.g., handling refresh tokens), and it required some fallback logic, but it works practically within the scope of individual development.

Summary

Key insights gained from operating Supabase Auth across Web and Mobile:

  1. Separate Supabase clients by use case — Cookie handling differs between Server Components, Server Actions, and the browser.
  2. Always include try-catch in setAll — Supabase's async callbacks run outside the request context.
  3. Distinguish auth strategies for public and protected routes — Using getSession() vs getUser() directly impacts performance.
  4. Client-side getUser() requires caching — Without it, requests will explode.
  5. Use signInWithIdToken + SecureStore for mobile — No OAuth redirects needed.

Authentication is the foundation of an app. Designing it robustly from the start makes future feature additions much easier.


About Storyie

Storyie is a diary app for recording daily events.

Discussion