Skip to content

Force Refresh Access Token Enhancements #2164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -386,9 +386,20 @@ export default function Component() {
}
}

async function fetchDataWithForceRefresh() {
try {
// Force a refresh of the access token
const token = await getAccessToken({ refresh: true })
// call external API with refreshed token...
} catch (err) {
// err will be an instance of AccessTokenError if an access token could not be obtained
}
}

return (
<main>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={fetchDataWithForceRefresh}>Fetch Data with Force Refresh</button>
</main>
)
}
Expand Down Expand Up @@ -525,20 +536,58 @@ export async function middleware(request: NextRequest) {

In some scenarios, you might need to explicitly force the refresh of an access token, even if it hasn't expired yet. This can be useful if, for example, the user's permissions or scopes have changed and you need to ensure the application has the latest token reflecting these changes.

The `getAccessToken` method provides an option to force this refresh.
The force refresh capability is available across **all environments**: client-side (browser), App Router server-side, and Pages Router server-side.

**Client-side (Browser):**

When calling `getAccessToken()` from the browser, you can pass an options object to force a refresh:

```tsx
"use client"

import { getAccessToken } from "@auth0/nextjs-auth0"

export default function Component() {
async function fetchData() {
try {
const token = await getAccessToken()
// call external API with token...
} catch (err) {
// err will be an instance of AccessTokenError if an access token could not be obtained
}
}

async function fetchDataWithForceRefresh() {
try {
// Force a refresh of the access token
const token = await getAccessToken({ refresh: true })
// call external API with refreshed token...
} catch (err) {
// err will be an instance of AccessTokenError if an access token could not be obtained
}
}

return (
<main>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={fetchDataWithForceRefresh}>Fetch Data with Force Refresh</button>
</main>
)
}
```

**App Router (Server Components, Route Handlers, Server Actions):**

When calling `getAccessToken` without request and response objects, you can pass an options object as the first argument. Set the `refresh` property to `true` to force a token refresh.

```typescript
// app/api/my-api/route.ts
import { getAccessToken } from '@auth0/nextjs-auth0';
import { auth0 } from '@/lib/auth0';

export async function GET() {
try {
// Force a refresh of the access token
const { token, expiresAt } = await getAccessToken({ refresh: true });
const { token, expiresAt } = await auth0.getAccessToken({ refresh: true });

// Use the refreshed token
// ...
Expand All @@ -555,16 +604,16 @@ When calling `getAccessToken` with request and response objects (from `getServer

```typescript
// pages/api/my-pages-api.ts
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
import { auth0 } from '@/lib/auth0';
import type { NextApiRequest, NextApiResponse } from 'next';

export default withApiAuthRequired(async function handler(
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
// Force a refresh of the access token
const { token, expiresAt } = await getAccessToken(req, res, {
const { token, expiresAt } = await auth0.getAccessToken(req, res, {
refresh: true
});

Expand All @@ -574,7 +623,7 @@ export default withApiAuthRequired(async function handler(
console.error('Error getting access token:', error);
res.status(error.status || 500).json({ error: error.message });
}
});
}
```

By setting `{ refresh: true }`, you instruct the SDK to bypass the standard expiration check and request a new access token from the identity provider using the refresh token (if available and valid). The new token set (including the potentially updated access token, refresh token, and expiration time) will be saved back into the session automatically.
Expand Down
24 changes: 22 additions & 2 deletions e2e/app-router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,33 @@ test("getAccessToken()", async ({ page }) => {
await page.fill('input[id="password"]', process.env.TEST_USER_PASSWORD!);
await page.getByText("Continue", { exact: true }).click();

// fetch a token
// request a token
const requestPromise = page.waitForRequest("/auth/access-token");
await page.getByText("Get token").click();
await page.getByText("Get access token").click();
const request = await requestPromise;
const tokenRequest = await (await request?.response())?.json();
expect(tokenRequest).toHaveProperty("token");
expect(tokenRequest).toHaveProperty("expires_at");
});

test("getAccessToken() with force refresh", async ({ page }) => {
await page.goto("/auth/login?returnTo=/app-router/client");

// fill out Auth0 form
await page.fill('input[id="username"]', "test@example.com");
await page.fill('input[id="password"]', process.env.TEST_USER_PASSWORD!);
await page.getByText("Continue", { exact: true }).click();

// force refresh a token
const requestPromise = page.waitForRequest("/auth/access-token?refresh=true");
await page.getByText("Force refresh token").click();
const request = await requestPromise;
const tokenRequest = await (await request.response())?.json();
expect(tokenRequest).toHaveProperty("token");
expect(tokenRequest).toHaveProperty("expires_at");

// Verify that the request URL contains the refresh parameter
expect(request.url()).toContain("refresh=true");
});

test("protected server route", async ({ page, context }) => {
Expand Down
24 changes: 22 additions & 2 deletions e2e/pages-router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,33 @@ test("getAccessToken()", async ({ page }) => {
await page.fill('input[id="password"]', process.env.TEST_USER_PASSWORD!);
await page.getByText("Continue", { exact: true }).click();

// fetch a token
// request a token
const requestPromise = page.waitForRequest("/auth/access-token");
await page.getByText("Get token").click();
await page.getByText("Get access token").click();
const request = await requestPromise;
const tokenRequest = await (await request?.response())?.json();
expect(tokenRequest).toHaveProperty("token");
expect(tokenRequest).toHaveProperty("expires_at");
});

test("getAccessToken() with force refresh", async ({ page }) => {
await page.goto("/auth/login?returnTo=/pages-router/client");

// fill out Auth0 form
await page.fill('input[id="username"]', "test@example.com");
await page.fill('input[id="password"]', process.env.TEST_USER_PASSWORD!);
await page.getByText("Continue", { exact: true }).click();

// force refresh a token
const requestPromise = page.waitForRequest("/auth/access-token?refresh=true");
await page.getByText("Force refresh token").click();
const request = await requestPromise;
const tokenRequest = await (await request.response())?.json();
expect(tokenRequest).toHaveProperty("token");
expect(tokenRequest).toHaveProperty("expires_at");

// Verify that the request URL contains the refresh parameter
expect(request.url()).toContain("refresh=true");
});

test("protected API route", async ({ page, request, context }) => {
Expand Down
12 changes: 11 additions & 1 deletion e2e/test-app/app/app-router/client/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ export default function Profile() {
)
}

const handleForceRefresh = async () => {
// TypeScript workaround: cast to any to use the overloaded signature
await (getAccessToken as any)({ refresh: true })
}

return (
<main>
<h1>Welcome, {user?.email}!</h1>
Expand All @@ -29,7 +34,12 @@ export default function Profile() {
await getAccessToken()
}}
>
Get token
Get access token
</button>
<button
onClick={handleForceRefresh}
>
Force refresh token
</button>
</main>
)
Expand Down
13 changes: 12 additions & 1 deletion e2e/test-app/pages/pages-router/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export default function Profile() {
)
}

const handleForceRefresh = async () => {
// TypeScript workaround: cast to any to use the overloaded signature
const token = await (getAccessToken as any)({ refresh: true })
setToken(token)
}

return (
<main>
<h1>Welcome, {user?.email}!</h1>
Expand All @@ -35,7 +41,12 @@ export default function Profile() {
setToken(token)
}}
>
Get token
Get access token
</button>
<button
onClick={handleForceRefresh}
>
Force refresh token
</button>
</main>
)
Expand Down
50 changes: 46 additions & 4 deletions src/client/helpers/get-access-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,52 @@ type AccessTokenResponse = {
expires_at?: number;
};

export async function getAccessToken(): Promise<string> {
const tokenRes = await fetch(
process.env.NEXT_PUBLIC_ACCESS_TOKEN_ROUTE || "/auth/access-token"
);
export type GetAccessTokenOptions = {
/**
* Force a refresh of the access token.
*/
refresh?: boolean;
};

/**
* Retrieves an access token from the `/auth/access-token` endpoint.
*
* @returns The access token string.
* @throws {AccessTokenError} If there's an error retrieving the access token.
*/
export async function getAccessToken(): Promise<string>;

/**
* Retrieves an access token from the `/auth/access-token` endpoint.
*
* @param options Configuration for getting the access token.
* @returns The access token string.
* @throws {AccessTokenError} If there's an error retrieving the access token.
*/
export async function getAccessToken(
options: GetAccessTokenOptions
): Promise<string>;
Comment on lines +16 to +33
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need these overloads?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To adhere to a no-contract change (adding new overloads)

Copy link
Member

@frederikprijck frederikprijck Jun 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not need those. We can just keep the one we have where options is marked optional, there is no point to the overloads here.


/**
* Retrieves an access token from the `/auth/access-token` endpoint.
*
* @param options Optional configuration for getting the access token.
* @returns The access token string.
* @throws {AccessTokenError} If there's an error retrieving the access token.
*/
export async function getAccessToken(
options?: GetAccessTokenOptions
): Promise<string> {
const searchParams = new URLSearchParams();
if (options?.refresh) {
searchParams.set("refresh", "true");
}

const baseUrl = `${process.env.NEXT_PUBLIC_ACCESS_TOKEN_ROUTE}` || "/auth/access-token";
const queryParams = searchParams.toString() ? `?${searchParams.toString()}` : "";
const url = `${baseUrl}${queryParams}`;

const tokenRes = await fetch(url);

if (!tokenRes.ok) {
// try to parse it as JSON and throw the error from the API
Expand Down
5 changes: 4 additions & 1 deletion src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export { useUser } from "./hooks/use-user";
export { getAccessToken } from "./helpers/get-access-token";
export {
getAccessToken,
type GetAccessTokenOptions
} from "./helpers/get-access-token";
export { Auth0Provider } from "./providers/auth0-provider";
82 changes: 82 additions & 0 deletions src/server/auth-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3624,6 +3624,88 @@ ca/T0LLtgmbMmxSv/MmzIg==
// validate that the session cookie has not been set
expect(response.cookies.get("__session")).toBeUndefined();
});

it("should force refresh the access token when refresh=true query parameter is provided", async () => {
const currentAccessToken = DEFAULT.accessToken;
const newAccessToken = "at_refreshed_456";

const secret = await generateSecret(32);
const transactionStore = new TransactionStore({
secret
});
const sessionStore = new StatelessSessionStore({
secret
});
const authClient = new AuthClient({
transactionStore,
sessionStore,

domain: DEFAULT.domain,
clientId: DEFAULT.clientId,
clientSecret: DEFAULT.clientSecret,

secret,
appBaseUrl: DEFAULT.appBaseUrl,

fetch: getMockAuthorizationServer({
tokenEndpointResponse: {
token_type: "Bearer",
access_token: newAccessToken,
scope: "openid profile email",
expires_in: 86400 // expires in 1 day
} as oauth.TokenEndpointResponse
})
});

// we use a non-expired token to ensure force refresh works even with valid tokens
const expiresAt = Math.floor(Date.now() / 1000) + 10 * 24 * 60 * 60; // expires in 10 days
const session: SessionData = {
user: {
sub: DEFAULT.sub,
name: "John Doe",
email: "john@example.com",
picture: "https://example.com/john.jpg"
},
tokenSet: {
accessToken: currentAccessToken,
scope: "openid profile email",
refreshToken: DEFAULT.refreshToken,
expiresAt
},
internal: {
sid: DEFAULT.sid,
createdAt: Math.floor(Date.now() / 1000)
}
};
const maxAge = 60 * 60; // 1 hour
const expiration = Math.floor(Date.now() / 1000 + maxAge);
const sessionCookie = await encrypt(session, secret, expiration);
const headers = new Headers();
headers.append("cookie", `__session=${sessionCookie}`);
const request = new NextRequest(
new URL("/auth/access-token?refresh=true", DEFAULT.appBaseUrl),
{
method: "GET",
headers
}
);

const response = await authClient.handleAccessToken(request);
expect(response.status).toEqual(200);
expect(await response.json()).toEqual({
token: newAccessToken,
scope: "openid profile email",
expires_at: expect.any(Number)
});

// validate that the session cookie has been updated with the new token
const updatedSessionCookie = response.cookies.get("__session");
const { payload: updatedSession } = await decrypt<SessionData>(
updatedSessionCookie!.value,
secret
);
expect(updatedSession.tokenSet.accessToken).toEqual(newAccessToken);
});
});

describe("handleBackChannelLogout", async () => {
Expand Down
Loading