Sessions
Sessions are used to identify an authenticated user.
Session strategy
User sessions are securely stored in the database. This allows active sessions to be managed in the security settings (i.e. you can log out all devices) and changes take effect immediately.
Access the session on the server
Directly
If you want to access the raw session call:
const session = await auth();
We recommend at least to use the deduplicated version:
const session = await dedupedAuth();
The difference is that you can call dedupedAuth
multiple times within a request and it will just execute once and cache the results with the other callers.
Via context
Sessions are also accessible via the auth context. This is the preferred way.
You can call either getAuthContext()
or getAuthOrganizationContext()
depending in which context you are in. Both provide you with the same session.
Example in a data function:
const ctx = await getAuthContext();
const session = ctx.session;
Example in a server action (automatically called via Next Safe Action middleware):
export const myServerAction = authActionClient
.action(async ({ ctx }) => {
const session = ctx.session;
});
Access the session on the client
You could use the built-in <SessionProvider />
provider and useSession
hook from Auth.js
, but accessing the session on the client is not really necessary. Let us know if you think otherwise!
Update the session from the server
The underlying library Auth.js
provides a metho called unstable_update
for this. Achromatic doesn't use the method so far.
Update the session from the client
We disabled client-side updates from the client. That's one thing less to worry about. If you want to enable it, please specify exactly which properties can be updated, otherwise you might have a security risk.
Auth check strategy
Achromatic uses the following strategy:
- No middleware checks: Only good for pre-checks (also mentioned in the Next.js docs).
- One layout auth check: Only good for pre-checks - remember that layouts don't re-render on navigation.
- Full auth check near the data: All data functions and server actions are checked for session, membership, roles and object access.
Redirect to sign in page
If you access a protected page, fetch data or try to mutate data the redirect is applied if the user is not authenticated or has an invalid session.