Shared Auth in Next.js and Expo: Practical?
In this article
Yes, sharing the same authentication and permission model between Next.js and Expo is practical, and for most projects it is the recommended approach. You can achieve this by centralizing your auth logic in a shared package or API layer, using token-based authentication (like JWT) that both platforms consume, and keeping permission checks on the server where they are enforceable. This saves significant development time, reduces bugs, and ensures a consistent security posture across web and mobile.
Why Share Auth at All?
Building separate authentication systems for a Next.js web app and an Expo mobile app doubles your work and creates security risks. If the web app checks permissions in one way and the mobile app does it differently, you might end up with inconsistent access control—a user could see data on one platform that they shouldn't on the other. Sharing the auth model means you define roles, permissions, and session handling once, then reuse that logic everywhere. It also simplifies maintenance: when you update a permission rule or add a new role, you change it in one place, not two.
How to Structure a Shared Auth System
The most practical way to share auth between Next.js and Expo is to treat authentication as a service that both clients call. Here is a typical architecture:
- Auth API: A backend (could be Next.js API routes, a separate Node/Express server, or a third-party service like Auth0 or Supabase) that handles login, logout, token refresh, and user profile retrieval.
- Shared types and utilities: A TypeScript package (e.g.,
shared-auth) that contains the types for users, roles, and permissions, plus helper functions to check permissions. Both Next.js and Expo import this package. - Client-side session handling: Next.js uses cookies (with middleware or server components) to manage sessions; Expo uses SecureStore or AsyncStorage to store tokens. Both store the same JWT or session token.
- Server-side enforcement: Every API request that requires authorization validates the token and checks permissions on the server. The client only uses permissions to hide or show UI elements, not as a security boundary.
- Storage: Next.js runs in a browser and server; cookies are the standard for session persistence. Expo runs on a device; you use SecureStore (for sensitive tokens) or AsyncStorage (for less critical data).
- Fetching data: In Next.js, you can fetch data on the server (in Server Components or
getServerSideProps) and pass the user down. In Expo, all data fetching happens client-side, so you need to handle loading states and token injection in your fetch calls. - Routing and guards: Next.js has middleware that can protect routes before they render. Expo uses React Navigation, and you implement route guards by checking the auth state before navigating.
- Token refresh: In Next.js, you can refresh tokens in middleware or API routes. In Expo, you need to intercept 401 responses and refresh the token, often using a fetch wrapper or an interceptor library.
- Server-side enforcement (mandatory): Every API endpoint must verify the user's role and permissions before returning data or performing an action. This is where the real security lives.
- Client-side rendering (optional but good UX): Use the shared permission utilities to conditionally render buttons, links, or entire screens. This improves user experience by hiding actions the user cannot perform, but it is not a security measure.
- Token storage differences: Next.js can read cookies on the server, but Expo cannot. Solution: store the token in a cookie for web and in SecureStore for mobile, and have your API accept the token via an
Authorizationheader. In Next.js, you can read the cookie and forward it as a header when making server-side requests. - Redirecting after login: In Next.js, you might redirect to a dashboard using
router.pushor a middleware. In Expo, you usenavigation.navigate. Keep the logic separate but the session state shared. - Session expiration: Users on mobile often have longer sessions. Implement a refresh token flow that works on both platforms. In Next.js, you can handle refresh in middleware; in Expo, you can use a fetch interceptor that retries the request after refreshing.
- Environment variables: Ensure both projects use the same API base URL. Use
EXPO_PUBLIC_prefix for Expo andNEXT_PUBLIC_for Next.js, and keep them in sync. - Small project / MVP: Use a single Next.js app with API routes, and have Expo call those routes. Share types by creating a
typesfolder and importing from a relative path or a simple npm workspace. - Medium project / multiple apps: Create a monorepo (using npm workspaces or Turborepo) with a
packages/authfolder that contains the shared logic. Both Next.js and Expo import from it. - Large enterprise: Consider using a dedicated auth service (like Auth0, Clerk, or Supabase) that provides SDKs for both Next.js and Expo. This offloads session management and security to a proven provider, and you only need to share the permission model (e.g., via a shared constants file).
Key Differences Between Next.js and Expo
While the auth model can be shared, the implementation details differ because of the environments:
Permission Model: Where to Enforce
A common misconception is that you can rely on client-side permission checks. That is not secure—anyone can modify the client code or call your API directly. The correct approach is:
For example, if you have an admin-only endpoint to delete a user, the server must check that the requester has the admin role. The Next.js app might hide the delete button from non-admins, and the Expo app might not show the admin screen at all, but both rely on the same server check to actually prevent unauthorized deletion.
Common Challenges and Solutions
Sharing auth is practical, but you will hit a few hurdles. Here are the most common ones and how to solve them:
How to Choose the Right Approach
Your choice depends on your project size and team:
Frequently Asked Questions
Can I use NextAuth.js with Expo?
NextAuth.js (now Auth.js) is designed for Next.js and works well on the web. For Expo, you can use the same backend but you need to handle the token exchange manually. A common pattern is to use NextAuth for the web and a custom login endpoint for Expo that returns a JWT, which you store in SecureStore. The JWT is then sent with every request to your API, and the API validates it using the same secret or public key.
Is it safe to store JWT in AsyncStorage on Expo?
AsyncStorage is not encrypted, so it is not the best place for sensitive tokens. Use expo-secure-store instead, which stores data in the device's secure enclave (Keychain on iOS, Keystore on Android). For a production app, always use SecureStore for access tokens and refresh tokens.
How do I handle permissions that change in real-time?
Permissions can change (e.g., a user gets promoted to admin). The safest way is to always fetch the user's current permissions from the server when they load the app or when they perform an action. You can cache the permissions for a short time but never rely on them for security. For real-time updates, you could use WebSockets or polling, but that is often overkill—just re-fetch the user profile after important events.
Should I use a monorepo to share code?
Yes, a monorepo is a clean way to share auth logic, types, and utility functions. Tools like npm workspaces or Turborepo allow you to have a shared package that both Next.js and Expo import. However, if you are not comfortable with monorepos, you can also publish a private npm package or simply copy the shared files (though that is less maintainable).
Can I use the same database session table for both platforms?
Yes, you should. The session is tied to the user, not the platform. If you use a session table (e.g., with a session ID stored in a cookie), both platforms can use the same table. For JWT-based auth, the token itself is stateless, so there is no session table—just validate the token on each request.
What is the easiest way to get started?
Start by defining your user and permission types in a shared file. Then create a simple login API that returns a JWT. In Next.js, store the token in an httpOnly cookie; in Expo, store it in SecureStore. Write a small helper function in each app that attaches the token to fetch requests. Finally, add server-side checks to your API routes. This gives you a working shared auth model in a few hours.