Skip to content

Commit

Permalink
feat(nextjs): Fetch user and session in parallel (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikosdouvlis committed Feb 25, 2022
1 parent 260d7cf commit e5c2620
Showing 1 changed file with 17 additions and 22 deletions.
39 changes: 17 additions & 22 deletions packages/nextjs/src/middleware/utils/getAuthData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ export async function getAuthData(

const getToken = async (options: GetSessionTokenOptions = {}) => {
if (options.template) {
throw new Error(
'Retrieving a JWT template during SSR will be supported soon.',
);
throw new Error('Retrieving a JWT template during SSR will be supported soon.');
}
return cookies['__session'] || null;
};
Expand All @@ -33,19 +31,18 @@ export async function getAuthData(
};

try {
const { status, sessionClaims, interstitial } =
await Clerk.base.getAuthState({
cookieToken: cookies['__session'],
clientUat: cookies['__client_uat'],
headerToken: headers.authorization?.replace('Bearer ', ''),
origin: headers.origin,
host: headers.host as string,
forwardedPort: headers['x-forwarded-port'] as string,
forwardedHost: headers['x-forwarded-host'] as string,
referrer: headers.referer,
userAgent: headers['user-agent'] as string,
fetchInterstitial: () => Clerk.fetchInterstitial(),
});
const { status, sessionClaims, interstitial } = await Clerk.base.getAuthState({
cookieToken: cookies['__session'],
clientUat: cookies['__client_uat'],
headerToken: headers.authorization?.replace('Bearer ', ''),
origin: headers.origin,
host: headers.host as string,
forwardedPort: headers['x-forwarded-port'] as string,
forwardedHost: headers['x-forwarded-host'] as string,
referrer: headers.referer,
userAgent: headers['user-agent'] as string,
fetchInterstitial: () => Clerk.fetchInterstitial(),
});

if (status === AuthStatus.Interstitial) {
ctx.res.writeHead(401, { 'Content-Type': 'text/html' });
Expand All @@ -57,12 +54,10 @@ export async function getAuthData(
return signedOutState;
}

const user = loadUser
? await users.getUser(sessionClaims.sub as string)
: undefined;
const session = loadSession
? await sessions.getSession(sessionClaims.sid as string)
: undefined;
const [user, session] = await Promise.all([
loadUser ? users.getUser(sessionClaims.sub as string) : Promise.resolve(undefined),
loadSession ? await sessions.getSession(sessionClaims.sid as string) : Promise.resolve(undefined),
]);

return {
sessionId: sessionClaims.sid as string,
Expand Down

0 comments on commit e5c2620

Please sign in to comment.