Skip to content

Commit d544f19

Browse files
Merge branch 'main' into fix/jwe-expiration
2 parents 2179d75 + 6bc280a commit d544f19

File tree

80 files changed

+2171
-374
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

80 files changed

+2171
-374
lines changed

.version

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
v4.4.2
1+
v4.5.0

CHANGELOG.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
# Change Log
22

3+
## [v4.5.0](https://github.com/auth0/nextjs-auth0/tree/v4.5.0) (2025-04-25)
4+
[Full Changelog](https://github.com/auth0/nextjs-auth0/compare/v4.4.2...v4.5.0)
5+
6+
**Added**
7+
- Extensive Cookie Configuration [\#2059](https://github.com/auth0/nextjs-auth0/pull/2059) ([tusharpandey13](https://github.com/tusharpandey13))
8+
- Allow refresh: true in getAccessToken() [\#2055](https://github.com/auth0/nextjs-auth0/pull/2055) ([tusharpandey13](https://github.com/tusharpandey13))
9+
- Allow SWR mutation in useUser hook [\#2045](https://github.com/auth0/nextjs-auth0/pull/2045) ([tusharpandey13](https://github.com/tusharpandey13))
10+
11+
**Changed**
12+
- Update README regarding access-token endpoint [\#2044](https://github.com/auth0/nextjs-auth0/pull/2044) ([frederikprijck](https://github.com/frederikprijck))
13+
14+
**Fixed**
15+
- Update tests for getAccessToken refresh flow [\#2068](https://github.com/auth0/nextjs-auth0/pull/2068) ([tusharpandey13](https://github.com/tusharpandey13))
16+
- fix: make configuration validation not throw [\#2034](https://github.com/auth0/nextjs-auth0/pull/2034) ([tusharpandey13](https://github.com/tusharpandey13))
17+
- feat: ensure cookie path is configurable [\#2050](https://github.com/auth0/nextjs-auth0/pull/2050) ([frederikprijck](https://github.com/frederikprijck))
18+
319
## [v4.4.2](https://github.com/auth0/nextjs-auth0/tree/v4.4.2) (2025-04-08)
420
[Full Changelog](https://github.com/auth0/nextjs-auth0/compare/v4.4.1...v4.4.2)
521

EXAMPLES.md

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
- [`beforeSessionSaved`](#beforesessionsaved)
2525
- [`onCallback`](#oncallback)
2626
- [Session configuration](#session-configuration)
27+
- [Cookie Configuration](#cookie-configuration)
2728
- [Database sessions](#database-sessions)
2829
- [Back-Channel Logout](#back-channel-logout)
2930
- [Combining middleware](#combining-middleware)
@@ -520,6 +521,65 @@ export async function middleware(request: NextRequest) {
520521
}
521522
```
522523

524+
### Forcing Access Token Refresh
525+
526+
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.
527+
528+
The `getAccessToken` method provides an option to force this refresh.
529+
530+
**App Router (Server Components, Route Handlers, Server Actions):**
531+
532+
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.
533+
534+
```typescript
535+
// app/api/my-api/route.ts
536+
import { getAccessToken } from '@auth0/nextjs-auth0';
537+
538+
export async function GET() {
539+
try {
540+
// Force a refresh of the access token
541+
const { token, expiresAt } = await getAccessToken({ refresh: true });
542+
543+
// Use the refreshed token
544+
// ...
545+
} catch (error) {
546+
console.error('Error getting access token:', error);
547+
return Response.json({ error: 'Failed to get access token' }, { status: 500 });
548+
}
549+
}
550+
```
551+
552+
**Pages Router (getServerSideProps, API Routes):**
553+
554+
When calling `getAccessToken` with request and response objects (from `getServerSideProps` context or an API route), the options object is passed as the third argument.
555+
556+
```typescript
557+
// pages/api/my-pages-api.ts
558+
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
559+
import type { NextApiRequest, NextApiResponse } from 'next';
560+
561+
export default withApiAuthRequired(async function handler(
562+
req: NextApiRequest,
563+
res: NextApiResponse
564+
) {
565+
try {
566+
// Force a refresh of the access token
567+
const { token, expiresAt } = await getAccessToken(req, res, {
568+
refresh: true
569+
});
570+
571+
// Use the refreshed token
572+
// ...
573+
} catch (error: any) {
574+
console.error('Error getting access token:', error);
575+
res.status(error.status || 500).json({ error: error.message });
576+
}
577+
});
578+
```
579+
580+
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.
581+
This will in turn, update the `access_token`, `id_token` and `expires_at` fields of `tokenset` in the session.
582+
523583
## `<Auth0Provider />`
524584

525585
### Passing an initial user from the server
@@ -626,6 +686,67 @@ export const auth0 = new Auth0Client({
626686
| absoluteDuration | `number` | The absolute duration after which the session will expire. The value must be specified in seconds. Default: `3 days`. |
627687
| inactivityDuration | `number` | The duration of inactivity after which the session will expire. The value must be specified in seconds. Default: `1 day`. |
628688

689+
## Cookie Configuration
690+
691+
You can configure the session cookie attributes either through environment variables or directly in the SDK initialization.
692+
693+
**1. Using Environment Variables:**
694+
695+
Set the desired environment variables in your `.env.local` file or your deployment environment:
696+
697+
```
698+
# .env.local
699+
# ... other variables ...
700+
701+
# Cookie Options
702+
AUTH0_COOKIE_DOMAIN='.example.com' # Set cookie for subdomains
703+
AUTH0_COOKIE_PATH='/app' # Limit cookie to /app path
704+
AUTH0_COOKIE_TRANSIENT=true # Make cookie transient (session-only)
705+
AUTH0_COOKIE_SECURE=true # Recommended for production
706+
AUTH0_COOKIE_SAME_SITE='Lax'
707+
```
708+
709+
The SDK will automatically pick up these values. Note that `httpOnly` is always set to `true` for security reasons and cannot be configured.
710+
711+
**2. Using `Auth0ClientOptions`:**
712+
713+
Configure the options directly when initializing the client:
714+
715+
```typescript
716+
import { Auth0Client } from "@auth0/nextjs-auth0/server"
717+
718+
export const auth0 = new Auth0Client({
719+
session: {
720+
cookie: {
721+
domain: '.example.com',
722+
path: '/app',
723+
transient: true,
724+
// httpOnly is always true and cannot be configured
725+
secure: process.env.NODE_ENV === 'production',
726+
sameSite: 'Lax',
727+
// name: 'appSession', // Optional: custom cookie name, defaults to '__session'
728+
},
729+
// ... other session options like absoluteDuration ...
730+
},
731+
// ... other client options ...
732+
});
733+
```
734+
735+
**Session Cookie Options:**
736+
737+
* `domain` (String): Specifies the `Domain` attribute.
738+
* `path` (String): Specifies the `Path` attribute. Defaults to `/`.
739+
* `transient` (Boolean): If `true`, the `maxAge` attribute is omitted, making it a session cookie. Defaults to `false`.
740+
* `secure` (Boolean): Specifies the `Secure` attribute. Defaults to `false` (or `true` if `AUTH0_COOKIE_SECURE=true` is set).
741+
* `sameSite` ('Lax' | 'Strict' | 'None'): Specifies the `SameSite` attribute. Defaults to `Lax` (or the value of `AUTH0_COOKIE_SAME_SITE`).
742+
* `name` (String): The name of the session cookie. Defaults to `__session`.
743+
744+
> [!INFO]
745+
> Options provided directly in `Auth0ClientOptions` take precedence over environment variables. The `httpOnly` attribute is always `true` regardless of configuration.
746+
747+
> [!INFO]
748+
> The `httpOnly` attribute for the session cookie is always set to `true` for security reasons and cannot be configured via options or environment variables.
749+
629750
## Database sessions
630751

631752
By default, the user's sessions are stored in encrypted cookies. You may choose to persist the sessions in your data store of choice.

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ You can customize the client by using the options below:
137137
| appBaseUrl | `string` | The URL of your application (e.g.: `http://localhost:3000`). If it's not specified, it will be loaded from the `APP_BASE_URL` environment variable. |
138138
| secret | `string` | A 32-byte, hex-encoded secret used for encrypting cookies. If it's not specified, it will be loaded from the `AUTH0_SECRET` environment variable. |
139139
| signInReturnToPath | `string` | The path to redirect the user to after successfully authenticating. Defaults to `/`. |
140-
| session | `SessionConfiguration` | Configure the session timeouts and whether to use rolling sessions or not. See [Session configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#session-configuration) for additional details. |
140+
| session | `SessionConfiguration` | Configure the session timeouts and whether to use rolling sessions or not. See [Session configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#session-configuration) for additional details. Also allows configuration of cookie attributes like `domain`, `path`, `secure`, `sameSite`, and `transient`. If not specified, these can be configured using `AUTH0_COOKIE_*` environment variables. Note: `httpOnly` is always `true`. See [Cookie Configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#cookie-configuration) for details. |
141141
| beforeSessionSaved | `BeforeSessionSavedHook` | A method to manipulate the session before persisting it. See [beforeSessionSaved](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#beforesessionsaved) for additional details. |
142142
| onCallback | `OnCallbackHook` | A method to handle errors or manage redirects after attempting to authenticate. See [onCallback](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#oncallback) for additional details. |
143143
| sessionStore | `SessionStore` | A custom session store implementation used to persist sessions to a data store. See [Database sessions](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#database-sessions) for additional details. |
@@ -147,6 +147,17 @@ You can customize the client by using the options below:
147147
| httpTimeout | `number` | Integer value for the HTTP timeout in milliseconds for authentication requests. Defaults to `5000` milliseconds |
148148
| enableTelemetry | `boolean` | Boolean value to opt-out of sending the library name and version to your authorization server via the `Auth0-Client` header. Defaults to `true`. |
149149

150+
## Session Cookie Configuration
151+
You can specify the following environment variables to configure the session cookie:
152+
```env
153+
AUTH0_COOKIE_DOMAIN=
154+
AUTH0_COOKIE_PATH=
155+
AUTH0_COOKIE_TRANSIENT=
156+
AUTH0_COOKIE_SECURE=
157+
AUTH0_COOKIE_SAME_SITE=
158+
```
159+
Respective counterparts are also available in the client configuration. See [Cookie Configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#cookie-configuration) for more details.
160+
150161
## Configuration Validation
151162

152163
The SDK performs validation of required configuration options when initializing the `Auth0Client`. The following options are mandatory and must be provided either through constructor options or environment variables:

docs/assets/hierarchy.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/assets/navigation.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)