We have released new versions of many AdonisJS packages since August. The biggest theme was performance, and Romain wrote about that work, and how we measured it, in Making AdonisJS faster, one bottleneck at a time . This post covers the rest: the new features, the major upgrades of Redis, OpenTelemetry and queues, and the fixes.
Before you upgrade, read two sections. Security fixes lists the packages that need an upgrade soon. Check these when you upgrade lists the fixes that change behavior your app may rely on.
Conditional container bindings
You can now register a binding that the container uses only when a condition is true. This is handy for feature flags, per-tenant implementations, or picking a service based on an environment variable.
Here, users with the new-payment flag get the beta payment provider, and everyone else gets Stripe.
import type { ApplicationService } from '@adonisjs/core/types'
import { HttpContext } from '@adonisjs/core/http'
import PaymentService from '#services/payment_service'
import StripeProvider from '#services/stripe_provider'
import BetaPaymentProvider from '#services/beta_payment_provider'
export default class AppProvider {
constructor(protected app: ApplicationService) {}
register() {
this.app.container.bind(PaymentService, () => {
return new StripeProvider()
})
this.app.container
.if(async (resolver) => {
if (!resolver.hasBinding(HttpContext)) {
return false
}
const ctx = await resolver.make(HttpContext)
return ctx.auth.user?.featureFlags.includes('new-payment') === true
})
.bind(PaymentService, () => {
return new BetaPaymentProvider()
})
}
}
The condition runs every time PaymentService is resolved, and it receives the resolver, so it can read the current HttpContext. Ace commands and queue jobs have no HTTP context, which is why the example checks for one first and otherwise falls back to the regular binding.
You can register several conditional bindings for the same key. The container tries them in order and uses the first one that matches. If none match, it uses the regular binding. Swaps still win over all of them, so the fakes in your tests keep working.
Conditional singletons
Use singleton instead of bind to create the instance only once. The condition is still checked on every resolution.
this.app.container
.if(() => env.get('SEARCH_DRIVER') === 'typesense')
.singleton(SearchService, (resolver) => {
return resolver.make(TypesenseSearchService)
})
Learn more in the dependency injection guide .
Try a rate limit before you enforce it
Rate limiters now have a dry run mode. In a dry run, a limiter counts requests as usual but never rejects them, so you can see how a new limit would affect real traffic before you turn it on.
export const apiThrottle = limiter.define('api', () => {
return limiter.allowRequests(100).every('1 hour').dryRun()
})
When a client goes over the limit, the request still goes through, and the limiter emits the new limit:exceeded event with dryRun: true. Log it to see who would have been throttled.
import emitter from '@adonisjs/core/services/emitter'
import logger from '@adonisjs/core/services/logger'
emitter.on('limit:exceeded', ({ key, response, dryRun }) => {
if (dryRun) {
logger.warn({ key, consumed: response.consumed }, 'request would have been throttled')
}
})
The key includes the name of the limiter, like api_ip_127.0.0.1, so you can tell which limit was hit.
Clients won't notice a dry run. No rate limit headers are sent, and your limitExceeded callback isn't called. Once you're happy with the numbers, remove .dryRun(). The real limit starts with fresh counters, because dry runs keep their own. You can also pass a boolean to dryRun(), to switch it on and off with an environment variable.
Outside dry runs, limit:exceeded fires on every rejected request, which is useful for logging abusive clients or sending metrics. See
monitoring rejected requests
in the rate limiting guide.
Thanks to MaximeMRF for contributing dry runs.
Session improvements
Encrypted sessions
The Redis and database stores can now encrypt session data. Until now, the data was only signed. That stops tampering, but anyone with access to Redis or the sessions table could still read it.
stores: {
redis: stores.redis({
connection: 'main',
encrypt: true,
}),
},
Existing sessions can't be read once you turn on encryption, so every user is logged out once.
Overlapping requests
Browsers often send several requests at once. A slow one could bring back a session that a logout or regenerate() had just destroyed. The Redis, database, file and DynamoDB stores no longer write back a destroyed session, and you don't need to change anything.
Two new options close the remaining gaps. refreshCookie: false sends the session cookie only when its ID changes, so a late response can't restore an old ID. renewMissingSessionId: true makes sure the ID of a destroyed session is never used again.
export default defineConfig({
age: '2h',
clearWithBrowser: true,
refreshCookie: false,
renewMissingSessionId: true,
})
Both are off by default, because they change how your app behaves. refreshCookie: false also stops refreshing the Max-Age of the cookie, so use it together with clearWithBrowser. The
sessions guide
walks through each case, including why logout should regenerate the session.
Field errors without a validation exception
session.flashInputErrors() lets you flash an error for a form field yourself, for example when an email is already taken. The @inputError tag of Edge and the Inertia adapter show it like any other validation error.
session.flashInputErrors({ email: 'This email is already registered' })
return response.redirect().back()
If you've been writing to inputErrorsBag by hand, this replaces it.
Choosing a store at install
node ace add @adonisjs/session now asks which store you want, instead of always setting up the cookie store. Pass --store to skip the prompt. With database, it also creates the migration for the sessions table.
node ace add @adonisjs/session --store=redis
Create and drop databases using Ace
Lucid now ships db:create and db:drop, so setting up a new machine or a CI job no longer means reaching for psql or docker exec.
node ace db:create
node ace db:drop
Both use your default connection, or the one you pass with --connection.
node ace db:create --connection=mysql
db:create leaves an existing database alone. For SQLite and LibSQL, the commands create or delete the database file, and they also work with PostgreSQL, MySQL, SQL Server and Redshift. In production, db:drop asks for confirmation unless you pass --force.
Thanks to batosai for both commands.
The QUERY HTTP method
QUERY is a new HTTP method, defined by
RFC 10008
. Like GET, it is safe and idempotent, and its responses can be cached. Like POST, it sends its input in the request body. It fits search and filter endpoints whose input is too large or too structured for a query string, where you would otherwise use a POST route that changes nothing.
Define a QUERY route with router.query(). (
http-server#159
)
import router from '@adonisjs/core/services/router'
import Product from '#models/product'
router.query('/products/search', async ({ request }) => {
const { category } = request.body()
return Product.query().where('category', category)
})
Make the URL of a QUERY route with urlFor.query(), or a signed one with signedUrlFor.query().
The bodyparser parses the body of QUERY requests, and QUERY is in its default allowedMethods. If your config/bodyparser.ts sets its own allowedMethods, add 'QUERY' to the list. (
bodyparser#87
)
Learn more in the routing guide .
A column alias prefix for models
Lucid aliases the columns of a model with its table name, so url on the semafor table becomes semafor_url. If the table also has a real semafor_url column, the two values got mixed up. Set columnAliasPrefix to give the aliases a different prefix. (
lucid#1214
, closes
lucid#1191
)
export default class Semafor extends BaseModel {
static table = 'semafor'
static columnAliasPrefix = 'semafor_alias'
}
For package authors
A configure hook can now add an import alias and create a directory without depending on Assembler (
core#5151
). It can also replace an env validation that already exists in start/env.ts, which is what --force should do (
assembler@cdd84d9
).
export async function configure(command: ConfigureCommand) {
const codemods = await command.createCodemods()
await codemods.addImportAlias('#channels/*', './app/channels/*.js')
await codemods.createDirectory('app/channels')
await codemods.defineEnvValidations({
overwrite: command.force,
variables: {
CHANNELS_DRIVER: `Env.schema.enum(['redis'] as const)`,
},
})
}
Without overwrite, node ace configure keeps the existing validation and now logs a warning about it, so a stale validation no longer goes unnoticed (
core@ed6bb1f
). EnvLoader also has a new getPaths() method that lists every env file it may load, in priority order, without touching the filesystem (
env@ba2eb12
).
Other features and improvements
- Core
node ace env:addaccepts--type=secret. The variable is validated withEnv.schema.secret(), and its value stays out of.env.example. Thanks to batosai . ( core#5157 )- The barrel files of
indexEntities()read the folders of controllers, events, listeners and transformers fromdirectoriesofadonisrc.ts. If you moved one of these folders, you no longer give it again toindexEntities(). Upgrade@adonisjs/assemblerto 8.6.2 too. ( core#5183 , assembler#132 )
- HTTP server
redirect()andredirectToPath()can forward the query string of the incoming request with{ forwardQueryString: true }. ( http-server@9088623 )
- Lucid
paginate()takes the name of the page parameter as its third argument, for pages that show two paginated lists. ( lucid#1162 )- The
make:*commands accept--force, andmake:modelpasses it on to the files it creates alongside the model. ( lucid@75178c1 ) Adapter.dbisprotectedandSeedsRunneris exported, so you can extend Lucid, for example to seed each tenant. ( lucid#1171 )
- Assembler
node ace serverestarts when an env file changes, including one loaded from a customENV_PATH. ( assembler@727f790 )
- Queue
queue:work --all-queuesprocesses every queue declared inconfig/queue.ts.--adapterlimits a worker, or the scheduler commands, to one adapter. ( queue 0.7.0 )
- Static
- The static middleware has a
prefixesoption. When you set it, only the requests under these prefixes look for a file inpublic/, and the other requests skip the filesystem. Romain explains why in his article . ( static#11 )
- The static middleware has a
- Vite
- The new
serverBuildDirectoryoption ofconfig/vite.tstellsloadServerModule()where to find the SSR build, whenvite.config.tswrites it to a customoutDir. ( vite#60 )
- The new
- OpenTelemetry
- SSE responses, including the ones from Transmit, are tagged with
http.connection_type=sse. ( otel#29 )
- SSE responses, including the ones from Transmit, are tagged with
Performance improvements
Romain wrote about most of the performance work, and how we measured it, in Making AdonisJS faster, one bottleneck at a time . This section covers three gains that his article doesn't.
Serializing nested resources
Transformers are now about five times faster on responses with nested relations. A paginated list of 20 users, with their profiles, posts and comments, used to take 1,482 µs to serialize. It now takes 276 µs.
Most of that time went into stack traces. Every call to transform() captured one, in case it received undefined and needed a helpful error. We now capture the stack trace only when that happens.
Preloading large relations
Preloading large relations is much faster. Loading the skills of 2,000 users, across 22,000 pivot rows, used to take 4.2 seconds. It now takes 0.1 seconds.
The slow part was matching the related rows to their parents. Lucid went through the full list of related rows for every parent. It now groups them by key in a single pass.
Resolving classes with no dependencies
The container now builds a class with no dependencies directly, without the full resolution pipeline. That makes container.make about three times faster for such classes, like a controller with no constructor dependencies.
Major upgrades
Redis 11 and ioredis 6
@adonisjs/redis 11 moves to ioredis 6, which talks to Redis using the RESP3 protocol by default. If you want to keep the protocol of ioredis 5, set protocol: 2 on the connection.
main: {
host: env.get('REDIS_HOST'),
port: env.get('REDIS_PORT'),
protocol: 2,
},
ioredis 6 also changes its default retry strategy to exponential backoff with jitter, and keeps TCP connections alive every 30 seconds. If your config sets its own retryStrategy, as the default config does, that one still applies. Any package that uses ioConnection directly must be on ioredis 6 as well.
There's no rush. The 10.x line stays on ioredis 5, and the session and queue packages work with both.
OpenTelemetry SDK 3
@adonisjs/otel 2 moves to version 3 of the OpenTelemetry JS SDK, and needs Node.js 22.15 or later.
The change you are most likely to notice is in your dashboards. HTTP and database spans now use only the stable semantic conventions, and the HTTP duration metrics have new names and are measured in seconds. Update the alerts and dashboards that read them.
The default config/otel.ts keeps working as it is. If you set up processors yourself, the singular options are gone, and processors now take an options object.
spanProcessor: new BatchSpanProcessor(exporter),
spanProcessors: [new BatchSpanProcessor({ exporter })],
The same goes for metricReader and logRecordProcessor. Code that imports from @opentelemetry/sdk-trace-base or sdk-trace-node now imports from @opentelemetry/sdk-trace.
Queues 0.7
@adonisjs/queue 0.7 changes how schedules and deduplication ids are stored, so the upgrade needs a few steps. Stop every worker, and every process that dispatches jobs. Then migrate the storage before you start the new version.
node ace queue:migrate
The command only does what is needed, so it is safe to run more than once. With Lucid on MySQL, or Kysely on PostgreSQL and MySQL, the old version stored schedule dates without a time zone. Pass the one it used, for example --timezone=Europe/Paris. A wrong value would shift every date, so the command refuses to guess.
The
release notes
list the behavior changes. The one most likely to surprise you is that maxRetries, retry, timeout and failOnTimeout in defaultJobOptions now apply.
The upgrade is worth it. On SIGTERM, queue:work now waits for the running jobs to finish before it closes its connections, so deploys no longer leave jobs to run twice. And in development, jobs reload without restarting the worker.
node ace queue:work --hmr
Check these when you upgrade
A few fixes change behavior that your app may rely on.
- Inertia type-checks page props again when the shared props have an optional key.
render()can now report type errors that were hidden before. ( inertia#121 ) - Ace keeps the values of array flags as strings.
--tags 1e3gives['1e3'], not[1000]. If a command needs numbers, convert them with theparseoption of the flag. ( ace#178 ) - Ace: a
stringornumberflag that is passed more than once takes the last value.serve --port=1 --port=2gives2. Before, the command got the array[1, 2]. Array flags still collect every value. ( ace#179 ) - HTTP server:
response.attachment()no longer quotes a simple file name, so the header isattachment; filename=hello.html. A name with non-ASCII characters also gets afilename*value. Both forms are valid, but a test that compares the header text needs an update. ( http-server#162 ) - HTTP server: a redirect to a URL that already has a query string merges the two query strings.
withQs({ success: 1 }).toPath('/users?page=2')now redirects to/users?page=2&success=1. Before, it added a second?. A key of the new query string replaces the same key of the URL. ( http-server#160 ) - Body parser: a
QUERYrequest with a missing or emptyContent-Typefails with status 400 and the codeE_INVALID_QUERY_CONTENT_TYPE. Send aContent-Typethat matches the body. ( bodyparser#87 ) - Core: if your app sets a folder in
directoriesofadonisrc.tsbut keeps its files in the oldapp/*folder, its barrel file now reads the folder indirectories. Move the files, correctdirectories, or givesourcetoindexEntities(). ( core#5183 ) - Limiter:
clear()of the Redis store deletes only the keys of the limiter. Before, it ranFLUSHDB, which also deleted the sessions, jobs and cache kept in the same Redis database. A Redis store without akeyPrefixnow throws when you callclear(). ( limiter#25 ) - CORS:
node ace configure @adonisjs/corsnow writesorigin: app.inDev ? true : []. If yourconfig/cors.tsstill hasorigin: true, list the origins of your production app. ( cors@f664532 ) - Lucid: the
isolationLevelofdb.transaction()now applies to manual transactions. Underrepeatable readorserializable, your code can get serialization failures to retry. ( lucid#1203 ) - Lucid:
trx.commit()anddb.transaction(callback)reject with the database error when the database rejects theCOMMIT, for example on a serialization failure in PostgreSQL. Before, the commit resolved, and theafter('commit')hooks ran for data that was not saved. ( lucid#1217 ) - Lucid:
-tis the alias of--transformerinmake:model. Before,-cmade a transformer instead of a controller. ( lucid#1180 ) - I18n:
formatRelativeTime()truncates past values towards zero, as it does for future values. 61 minutes ago gives1 hour ago. Before, it gave2 hours ago. ( i18n#156 ) - Vite: when
serverEntryPointsis empty, production builds no longer create an SSR environment. If another Vite plugin sets one up, check your build. ( vite#44 )
Security fixes
Upgrade if you use these packages. The v6 lines got the same fixes.
@adonisjs/http-server9.3.0 and 8.2.3 encode route parameters in generated URLs, which closes an open redirect throughredirect().toRoute()( GHSA-2m6q-8v3h-jqww ). 9.3.2 decodes request paths in linear time. Before, a 16 KB path took about 6.5 ms of CPU. ( http-server@8ff0eb0 )@adonisjs/ally6.3.1 and 5.1.2 treat a missing state cookie as a state mismatch, which closes a login CSRF ( GHSA-j577-w94j-8p3p ).@adonisjs/bodyparser11.0.5 and 10.1.6 fix several ways to crash or stall the process with a multipart request ( GHSA-8w45-cghr-9rh4 , GHSA-jf2h-r4qp-9rp8 ).file.clientNamenow decodes%2F, so sanitize it before you pass it tofile.move().@adonisjs/inertia5.0.4 escapes<in the page payload of the@inertiatag, so stored user text can no longer break the first page load ( GHSA-p3rg-578c-4g4r ).@adonisjs/cors3.0.1 checks the headers of a preflight request in linear time. Before, a 13.7 KB header took about 10 ms of event loop time. ( cors@8c38d96 )@adonisjs/mail10.4.1 moves to Nodemailer 10, for the advisories that affect Nodemailer 9. ( mail#187 )
Other fixes
- Ace
- A command fails when its
executingorexecutedhook throws. ( ace#176 ) - Redefining an alias drops the arguments of the old one. ( ace@d31e411 )
- The original error is kept when the detailed error output fails. ( ace#171 )
- The "Did you mean?" list shows the closest commands and namespaces first. ( ace#180 )
- A command fails when its
- Assembler
- The build refuses an output directory at or above the project root, so it can no longer delete project files.
- The dev server and test runner wait for the indexes to regenerate before they restart.
- The dev server and
node ace testcheck that the port is free on theHOSTwhere the app listens. ( assembler#126 ) - The dev server uses
VITE_HMR_PORTfor the HMR websocket, so two apps that start at the same time no longer pick the same port. ( assembler#129 ) - The build copies the files of nested folders on filesystems such as Docker volumes. ( assembler#127 )
- Auth
- Content
- Concurrent calls to
Collection.load()share one run of the loader. A static build that renders many pages at once no longer makes one API request for each page. ( content#7 )
- Concurrent calls to
- Core
node ace env:add --type=enumwrites a rule that accepts the value, and asks for the values when you don't pass--enum-values. ( core#5177 )node ace configure <package> --forcereplaces the env validations of the package. ( core@4a83aee )- The build fails when the commands index cannot be generated. ( core@184621f )
- Env
- A variable that refers to itself, or a cycle of references, resolves to an empty string instead of crashing the app at boot. ( env#56 )
- Fold
- A class with a static
toStringmethod is detected as a class. ( fold#75 )
- A class with a static
- HTTP server
trustProxyaccepts a comma-separated list and an array of ranges. ( http-server#143 )router.matchers.uuid()rejects letters afterf. ( http-server#144 )- An error thrown while matching a route reaches the error handler, also in an app without global middleware. ( http-server#146 )
- Requests behind a trusted proxy use the first
X-Forwarded-Hostvalue. - Sending a native
Responsekeeps all itsSet-Cookieheaders. request.hasValidSignature()accepts a signed URL with percent-encoded route params, such asmy invoice.pdforcafé. ( http-server#155 )
- HTTP transformers
isLucidPaginatorMetaData()narrows the metadata to the types that Lucid'sgetMeta()returns. ( http-transformers#17 )
- Inertia
- Clear history survives redirects. ( inertia#106 )
- A successful submission with an error bag calls
onSuccess. ( inertia#118 ) - The types of the router methods are kept. ( inertia#108 )
- Lock
- The Redis store opens its connection on first use. ( lock#7 )
- Lucid
- Two migration runners can no longer apply the same migration. ( lucid#1215 )
- A row with a
nulllocal key no longer breaks the preload of the whole collection. ( lucid#1189 ) - Preloads inside a transaction no longer trigger the PostgreSQL query queue warning. ( lucid#1200 )
toKnex()andtoSQL()of a relationship subquery keep its constraints. ( lucid#1208 )update()withreturningresolves column names and raw values. ( lucid#1201 )fill(),merge()andcreate()no longer accept$columns. ( lucid#1176 )schema:generatehandles tables with the same name in different schemas, and columns such asplayer1_id. ( lucid#1216 , lucid@b23d814 )
- Mail
- The Cloudflare transport accepts names with non-ASCII characters. ( mail#185 )
- OpenTelemetry
OTEL_SDK_DISABLED=trueskips the setup. ( otel@7663799 )
- Redis
- Quitting a lazy connection no longer connects to the server first. ( redis#75 )
- String helpers
- Transmit
node ace codegenexits when the app uses Transmit, including with the Redis transport. ( transmit#46 )
- Vite
- Requests that the client aborts while Vite serves them no longer stay open and block shutdown. ( vite#54 )
- Vite starts before the app accepts requests.
@viteUrlworks in the CSP when assets are served from an HTTPS URL.- A build with
serverEntryPointsand no SSR manifest fails with an error that saysloadServerModule()needs the manifest. Before, the app failed later, in production. ( vite#60 )
Upgrading
The minor and patch releases need no changes, apart from the items in "Check these when you upgrade".
npm update
npm update stays within the ranges of your package.json, so it doesn't install the major versions of Redis, OpenTelemetry and queues. Install those yourself when you're ready.
npm i @adonisjs/redis@latest @adonisjs/otel@latest @adonisjs/queue@latest
Apps created before September 2026 can switch to the
smaller entry points
of @adonisjs/core.
import { indexEntities } from '@adonisjs/core'
import { indexEntities } from '@adonisjs/core/generators'
const { Ignitor, prettyPrintError } = await import('@adonisjs/core')
const { Ignitor, prettyPrintError } = await import('@adonisjs/core/ignitor')
import { Ignitor, prettyPrintError } from '@adonisjs/core'
import { Ignitor, prettyPrintError } from '@adonisjs/core/ignitor'
- Conditional container bindings
- Try a rate limit before you enforce it
- Session improvements
- Create and drop databases using Ace
- The QUERY HTTP method
- A column alias prefix for models
- For package authors
- Other features and improvements
- Performance improvements
- Major upgrades
- Check these when you upgrade
- Security fixes
- Other fixes
- Upgrading