Skip to content

Commit c9d6245

Browse files
author
Paul Asjes
authored
Preserve search params on return (#17)
1 parent 49e56e5 commit c9d6245

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/authkit-callback-route.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export function authLoader(options: HandleAuthOptions = {}) {
1313

1414
const code = url.searchParams.get('code');
1515
const state = url.searchParams.get('state');
16-
const returnPathname = state ? JSON.parse(atob(state)).returnPathname : null;
16+
let returnPathname = state ? JSON.parse(atob(state)).returnPathname : null;
1717

1818
if (code) {
1919
try {
@@ -27,7 +27,19 @@ export function authLoader(options: HandleAuthOptions = {}) {
2727
url.searchParams.delete('state');
2828

2929
// Redirect to the requested path and store the session
30-
url.pathname = returnPathname ?? returnPathnameOption;
30+
returnPathname = returnPathname ?? returnPathnameOption;
31+
32+
// Extract the search params if they are present
33+
if (returnPathname.includes('?')) {
34+
const newUrl = new URL(returnPathname, 'https://example.com');
35+
url.pathname = newUrl.pathname;
36+
37+
for (const [key, value] of newUrl.searchParams) {
38+
url.searchParams.append(key, value);
39+
}
40+
} else {
41+
url.pathname = returnPathname;
42+
}
3143

3244
// The refreshToken should never be accesible publicly, hence why we encrypt it in the cookie session
3345
// Alternatively you could persist the refresh token in a backend database

src/session.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async function authkitLoader<Data = unknown>(
115115

116116
if (!session) {
117117
if (ensureSignedIn) {
118-
const returnPathname = new URL(request.url).pathname;
118+
const returnPathname = getReturnPathname(request.url);
119119
const cookieSession = await getSession(request.headers.get('Cookie'));
120120

121121
throw redirect(await getAuthorizationUrl({ returnPathname }), {
@@ -253,4 +253,10 @@ async function verifyAccessToken(accessToken: string) {
253253
}
254254
}
255255

256+
function getReturnPathname(url: string): string {
257+
const newUrl = new URL(url);
258+
259+
return `${newUrl.pathname}${newUrl.searchParams.size > 0 ? '?' + newUrl.searchParams.toString() : ''}`;
260+
}
261+
256262
export { encryptSession, terminateSession, authkitLoader };

0 commit comments

Comments
 (0)