How to share session between 2 web apps that have same apex domain
To share sessions across two separate web projects, typically hosted on different domains or subdomains, you'll face some challenges due to security restrictions imposed by web browsers (such as the Same-Origin Policy). Here are a few approaches you can consider:
-
Centralized Session Store: Use a centralized session store that both web projects can access. This could be a database (like Redis or MongoDB) or a dedicated session store service (like AWS ElastiCache or Azure Redis Cache). Both projects would need to implement session management logic that interacts with this central store.
-
Token-Based Authentication: Instead of traditional sessions, use tokens (like JSON Web Tokens, JWTs) for authentication. The tokens can be issued by one project and verified by the other using a shared secret or a centralized authentication service.
-
Single Sign-On (SSO): Implement a Single Sign-On solution where users authenticate once and get a token that can be used across both projects. Services like OAuth2 providers (Google, Facebook, etc.) or enterprise SSO solutions (Auth0, Okta, etc.) can be used for this purpose.
-
Cross-Domain Cookies: If your projects are subdomains of the same parent domain (
project1.example.com
andproject2.example.com
), you can set cookies with a domain attribute that specifies.example.com
. This allows cookies to be shared across subdomains. -
API Gateway: Use an API Gateway or a proxy server that sits in front of both projects and handles session management and authentication. This way, both projects can delegate session handling to the gateway.