MCPcopy Create free account
hub / github.com/Linen-dev/linen.dev / useSession

Function useSession

packages/auth-client/src/client/index.tsx:162–193  ·  view source on GitHub ↗
(options?: UseSessionOptions<R>)

Source from the content-addressed store, hash-verified

160 *
161 */
162export function useSession<R extends boolean>(options?: UseSessionOptions<R>) {
163 if (!SessionContext) {
164 throw new Error('React Context is unavailable in Server Components');
165 }
166
167 // @ts-expect-error Satisfy TS if branch on line below
168 const value: SessionContextValue<R> = React.useContext(SessionContext);
169 if (!value && process.env.NODE_ENV !== 'production') {
170 throw new Error('`useSession` must be wrapped in a <SessionProvider />');
171 }
172
173 const { required, onUnauthenticated } = options || {};
174
175 const requiredAndNotLoading = required && value.status === 'unauthenticated';
176
177 React.useEffect(() => {
178 if (requiredAndNotLoading) {
179 const url = `${__LINEN_AUTH.basePath}/signin?${new URLSearchParams({
180 error: 'SessionRequired',
181 callbackUrl: window.location.href,
182 })}`;
183 if (onUnauthenticated) onUnauthenticated();
184 else window.location.href = url;
185 }
186 }, [requiredAndNotLoading, onUnauthenticated]);
187
188 if (requiredAndNotLoading) {
189 return { data: value.data, status: 'loading' } as const;
190 }
191
192 return value;
193}
194
195export async function getSession(params?: GetSessionParams) {
196 const session = await fetchData<Session>(

Callers 3

PostHogUserFunction · 0.90
PageLayoutFunction · 0.90
ProfileFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected