---
url: https://maximemrf.github.io/adonisjs-jwt/upgrading/1.0.md
description: >-
  Upgrade @maximemrf/adonisjs-jwt from 0.x to 1.0: breaking changes, new
  defaults and the steps to migrate an AdonisJS app.
---

# Upgrading to 1.0

Version 1.0 hardens the security defaults and stabilizes the public API. Most applications only need to check the points below and update a few lines of configuration.

```sh
npm i @maximemrf/adonisjs-jwt@^1.0.0
```

`@adonisjs/auth` is now a peer dependency. It is already installed if you use the guard.

## Breaking changes

### Signing key derived from the application key

Without `secret`, tokens were signed with the raw application key. They are now signed with a key derived from it, see [Security](/guide/security#signing-key).

* **Access tokens issued by 0.9 are rejected** after the upgrade. Clients get a `401` and must refresh their token or log in again. Refresh tokens are stored in the database and **stay valid**, so clients with a refresh token don't have to log in again.
* The application key must be at least 32 characters, otherwise the guard throws at startup. AdonisJS generates 32 characters keys by default.

Applications that set `secret` keep their tokens, as long as the secret is at least 32 characters. A shorter secret now stops the app from booting: replace it with a longer one (all tokens are then rejected), see [Security](/guide/security#signing-key).

No database migration is needed: the `jwt_refresh_tokens` table of 0.9 works as is.

### Access tokens expire after 1 hour by default

Without `tokenExpiresIn`, access tokens never expired. They now expire after `1h`. Set `tokenExpiresIn` to keep another lifetime.

A `content` function that sets `exp` itself no longer compiles, and throws when issuing a token: remove `exp` and use `tokenExpiresIn`. The same goes for `iss` and `aud` when `issuer` and `audience` are configured.

### JWKS requires issuer and audience

In JWKS mode, the guard throws at startup if `issuer` is missing, or if neither `audience` nor `verifyPayload` is set. Set them to the values of your identity provider, see [JWKS](/guide/jwks). If your provider's tokens have no `aud` claim specific to your API (Amazon Cognito access tokens, for example), check the claim that identifies your API with [`verifyPayload`](/guide/jwks#check-other-claims) instead of `audience`.

### The configuration is checked when the app boots

The guard options are checked when `config/auth.ts` is loaded, so a wrong configuration stops the app from booting with an explicit error, instead of failing on every request:

* `tokenExpiresIn` and `refreshTokenExpiresIn` must be a positive number of seconds, or a duration of at least 1 second with a unit (`'15m'`, `'7d'`). A string without unit, such as `'3600'` read from an env variable, is rejected: validate the variable as a number in `start/env.ts`, or add a unit.
* `clockTolerance` must not be negative.
* `secret` and the application key must be at least 32 characters.
* With asymmetric keys, `publicKey` must belong to the same key pair as `privateKey`.
* With `jwks`, `jwks.jwksUri` is required.

Ace commands that boot the application, such as `node ace migration:run`, fail too: fix the configuration before deploying.

### revoke() fails when nothing is revoked

`revoke()` used to succeed silently when the request had no valid refresh token. It now throws `E_UNAUTHORIZED_ACCESS` (a `401`) after clearing the cookies. A client that sends its access token instead of its refresh token on logout now learns that its refresh token was not revoked, see [Revoke a refresh token](/guide/refresh-tokens#revoke-a-refresh-token).

Your logout route needs no change: an API client gets the `401`. If logging out must always succeed, for example on a page, ignore the error, the cookies are cleared anyway:

```ts
import { errors } from '@adonisjs/auth'

router.post('logout', async ({ auth, response }) => {
  try {
    await auth.use('jwt').revoke()
  } catch (error) {
    // only "nothing to revoke": a database outage must still fail the request
    if (!(error instanceof errors.E_UNAUTHORIZED_ACCESS)) throw error
  }
  return response.redirect('/login')
})
```

Clients that keep the tokens in memory must send the refresh token on logout, in the body or the `Authorization` header, see [Single-page apps](/guide/spa#log-out).

### 401 responses follow the Accept header

`401` responses were always plain text. JSON requests now get a JSON body, and page or Inertia requests are redirected to the login route of the `auth` middleware, see [Authentication](/guide/authentication). If your exception handler already formats these errors, it keeps precedence.

### Refresh token in the query string

A refresh token sent in the query string (`?refreshToken=…`) is ignored. Send it in the request body, a cookie or the `Authorization` header.

### Refresh token body field follows refreshTokenName

The refresh token was always read from the `refreshToken` body field. It is now read from the field named after `refreshTokenName`. If you set a custom `refreshTokenName` and your clients send the token in a `refreshToken` field, rename the field in your clients.

### Token lookup order

* **Refresh token**: when `useCookiesForRefreshToken` is enabled, the cookie is read before the request body.
* **Access token**: the `Authorization` header is read before the cookie, and the cookie is only read when `useCookies` is enabled. If you set the `token` cookie yourself without `useCookies`, enable `useCookies`.

See [Cookies and token transport](/guide/token-transport).

### Lifetimes in the generate() result are in seconds

`expiresIn` and `refreshTokenExpiresIn`, returned by `generate()` and `generateWithRefreshToken()`, are now a number of seconds. They used to repeat the config value as is, so `'1h'` by default.

```jsonc
"expiresIn": "1h", // [!code --]
"expiresIn": 3600, // [!code ++]
```

If a client reads these fields (to schedule a refresh, or to compute an expiration date), update it to read a number of seconds. Clients that ignore them are not affected.

### Refresh tokens expire after 7 days by default

Without `refreshTokenExpiresIn`, refresh tokens used to never expire. They now expire after 7 days. Set `refreshTokenExpiresIn` to keep a longer lifetime. Refresh tokens issued before the upgrade have no expiration in the database and stay valid until they are used. To make them expire too, delete them, or set their `expires_at` column.

### Public types

These changes only affect TypeScript code that uses the types of the package:

* **Custom user providers** must declare the type of the user they return, like the providers of `@adonisjs/auth` do:

  ```ts
  export class ServiceUserProvider implements JwtUserProviderContract<Service> {
    declare [symbols.PROVIDER_REAL_USER]: Service // [!code ++]
  ```

* **`content` must return `userId`** unless `getUserId` is set, since the guard reads the user id from this claim. With `getUserId`, `content` can use another claim, such as `sub`.

* **`@maximemrf/adonisjs-jwt/types` only exports types.** Import `DEFAULT_TOKEN_EXPIRES_IN` from the main entrypoint.

* **`JwtGuardOptions` has no `driver` option.** Custom drivers were never supported.

* The type of the `jwtGuard()` config is exported as `JwtGuardConfig`.

## Other changes

These changes don't require any action.

* **Imports**: import from the main entrypoint. The old path still works.

  ```ts
  import { jwtGuard } from '@maximemrf/adonisjs-jwt/jwt_config' // [!code --]
  import { jwtGuard } from '@maximemrf/adonisjs-jwt' // [!code ++]
  ```

* **Typed `content`**: `user.getOriginal()` is typed after your model, the generic signature and the cast are no longer needed.

  ```ts
  content: <T>(user: JwtGuardUser<T>) => ({ // [!code --]
    email: (user.getOriginal() as User).email, // [!code --]
  content: (user) => ({ // [!code ++]
    email: user.getOriginal().email, // [!code ++]
    userId: user.getId(),
  }),
  ```

  Then remove the imports that are no longer used, such as `JwtGuardUser` and the model imported for the cast, otherwise `tsc` reports them with `noUnusedLocals`.

* **AdonisJS v7 apps without `secret`**: the guard now reads `APP_KEY` from the environment when `config/app.ts` has no `appKey`, which is the case of new AdonisJS v7 apps. If you added `export const appKey = env.get('APP_KEY')` to `config/app.ts` for 0.9, you can remove it: both give the same signing key, and tokens stay valid.

* **`JwtGuard` is exported** from the package entrypoint, for guards built without `jwtGuard()`. Its lifetime option is `tokenExpiresIn`, like in `jwtGuard()`.

* **`node ace configure`** now adds the guard to `config/auth.ts` and the `refreshTokens` provider to the user model, see [Installation](/guide/installation).

* **JWKS defaults**: key fetches are cached and rate limited by default, see [Key fetching](/guide/jwks#key-fetching).

* **`revoke()`** also clears the access and refresh token cookies.

* **`refreshTokenAbilities`** are now checked by `generateWithRefreshToken()`.

* **`user.currentToken`** holds the new access token after `generateWithRefreshToken()`, which no longer returns `undefined` in its type.

* **Concurrent refreshes**: when two requests use the same refresh token, the one that fails no longer leaves the guard authenticated.
