The Helpers module provides a comprehensive collection of utility functions for common tasks in AdonisJS applications. It includes utilities for string manipulation, cryptographic operations, file system operations, assertions, and type checking.
Import
import {
fsReadAll,
fsImportAll,
base64,
compose,
Secret,
safeEqual,
MessageBuilder,
VerificationToken,
string,
assertExists,
is
} from '@adonisjs/core/helpers'
File System Utilities
fsReadAll
Recursively read all files from a directory.
The directory path to read files from
Optional configuration for reading filesoptions.filter
(path: string) => boolean
Filter function to include/exclude files
Whether to sort the results alphabetically
Returns: Promise<string[]> - Array of file paths
import { fsReadAll } from '@adonisjs/core/helpers'
const files = await fsReadAll(new URL('./app/controllers', import.meta.url))
console.log(files) // ['UsersController.ts', 'PostsController.ts']
fsImportAll
Recursively import all modules from a directory.
The directory path to import modules from
Optional configuration for importing modulesoptions.filter
(path: string) => boolean
Filter function to include/exclude files
Returns: Promise<Record<string, any>[]> - Array of imported modules
import { fsImportAll } from '@adonisjs/core/helpers'
const events = await fsImportAll(new URL('./app/events', import.meta.url))
events.forEach(event => {
console.log(event.default)
})
Cryptographic Utilities
base64
Base64 encoding and decoding utilities.
base64.encode
Encode a string or buffer to base64.
Whether to use URL-safe encoding
Returns: string - Base64 encoded string
import { base64 } from '@adonisjs/core/helpers'
const encoded = base64.encode('sensitive data')
const urlSafe = base64.encode('data', true)
base64.decode
Decode a base64 string.
The base64 string to decode
The character encoding to use
Returns: string - Decoded string
const decoded = base64.decode(encoded)
base64.urlEncode
Encode data using URL-safe base64 encoding.
Returns: string - URL-safe base64 encoded string
const urlEncoded = base64.urlEncode('data with special chars')
base64.urlDecode
Decode a URL-safe base64 string.
The URL-safe base64 string to decode
The character encoding to use
Returns: string - Decoded string
const decoded = base64.urlDecode(urlEncoded)
safeEqual
Perform a constant-time comparison of two strings or buffers to prevent timing attacks.
Returns: boolean - True if values are equal
import { safeEqual } from '@adonisjs/core/helpers'
const isEqual = safeEqual(hash1, hash2)
if (isEqual) {
console.log('Hashes match')
}
Secret
Wrapper class for managing sensitive data that should not be logged or serialized.
import { Secret } from '@adonisjs/core/helpers'
const apiKey = new Secret('my-api-key-12345')
// Safe to log - won't expose the secret
console.log(apiKey) // Secret {}
// Get the actual value when needed
const actualValue = apiKey.release()
Methods
Returns the underlying secret value
compose
Compose multiple classes or mixins into a single class.
Array of mixin classes to compose
Returns: Constructor - Composed class
import { compose } from '@adonisjs/core/helpers'
class Base {
name = 'base'
}
const Mixin1 = (superclass) => class extends superclass {
method1() { return 'mixin1' }
}
const Mixin2 = (superclass) => class extends superclass {
method2() { return 'mixin2' }
}
const Composed = compose(Base, Mixin1, Mixin2)
const instance = new Composed()
MessageBuilder
Builder class for constructing formatted messages.
import { MessageBuilder } from '@adonisjs/core/helpers'
const message = new MessageBuilder()
.add('Error: %s', 'Something went wrong')
.add('Code: %d', 500)
.toString()
VerificationToken
Abstract class for creating secure verification tokens with hash storage.
import { VerificationToken } from '@adonisjs/core/helpers'
class UserToken extends VerificationToken {
declare identifier: string
declare tokenableId: string
declare hash: string
declare expiresAt: Date
constructor(user: User, secret: Secret<string>) {
super()
this.tokenableId = user.id
this.computeValue(secret)
}
}
Static Methods
VerificationToken.decode
Decode a publicly shared token.
The token string to decode
Returns: { identifier: string; secret: Secret<string> } | null
const decoded = VerificationToken.decode(tokenString)
if (decoded) {
console.log(decoded.identifier)
console.log(decoded.secret.release())
}
VerificationToken.createTransientToken
Create a transient token for database storage.
userId
string | number | BigInt
required
The user ID for whom the token is created
The size of the random token seed
Token expiration time (e.g., ‘2h’, ‘30m’, or seconds as number)
Returns: { userId: string | number | BigInt; expiresAt: Date; secret: Secret<string>; hash: string }
const token = VerificationToken.createTransientToken(user.id, 40, '2 hours')
// Store token.hash and token.expiresAt in database
// Return token.secret to user
VerificationToken.seed
Generate a random seed and its hash.
The length of the random token to generate
Returns: { secret: Secret<string>; hash: string }
const { secret, hash } = VerificationToken.seed(40)
Instance Methods
isExpired
Check if the token has expired.
Returns: boolean - True if token is expired
if (token.isExpired()) {
console.log('Token has expired')
}
verify
Verify a secret against the stored hash.
Returns: boolean - True if secret matches hash
const isValid = token.verify(secret)
if (isValid) {
console.log('Token is valid')
}
String Utilities
Comprehensive string manipulation utilities.
import string from '@adonisjs/core/helpers/string'
string.camelCase
Convert a string to camelCase.
Returns: string
string.camelCase('hello_world') // 'helloWorld'
string.camelCase('Hello World') // 'helloWorld'
string.snakeCase
Convert a string to snake_case.
Returns: string
string.snakeCase('HelloWorld') // 'hello_world'
string.snakeCase('helloWorld') // 'hello_world'
string.pascalCase
Convert a string to PascalCase.
Returns: string
string.pascalCase('hello_world') // 'HelloWorld'
string.pascalCase('hello world') // 'HelloWorld'
string.capitalCase
Convert a string to Capital Case.
Returns: string
string.capitalCase('hello_world') // 'Hello World'
string.sentenceCase / string.toSentence
Convert a string to sentence case.
Returns: string
string.toSentence('hello_world') // 'Hello world'
string.toSentence('firstName') // 'First name'
string.dashCase
Convert a string to dash-case (kebab-case).
Returns: string
string.dashCase('HelloWorld') // 'hello-world'
string.dotCase
Convert a string to dot.case.
Returns: string
string.dotCase('HelloWorld') // 'hello.world'
string.noCase
Convert a string to no case (space separated lowercase).
Returns: string
string.noCase('HelloWorld') // 'hello world'
string.titleCase
Convert a string to Title Case.
Returns: string
string.titleCase('hello_world') // 'Hello World'
string.pluralize
Convert a word to its plural form.
Returns: string
string.pluralize('user') // 'users'
string.pluralize('person') // 'people'
string.singular
Convert a word to its singular form.
Returns: string
string.singular('users') // 'user'
string.singular('people') // 'person'
string.ordinal / string.ordinalize
Convert a number to its ordinal form.
Returns: string
string.ordinalize(1) // '1st'
string.ordinalize(22) // '22nd'
string.ordinalize(103) // '103rd'
string.random / string.generateRandom
Generate a cryptographically secure random string.
The length of the string to generate
Returns: string
string.generateRandom(16) // 'a1b2c3d4e5f6g7h8'
string.generateRandom(32) // Long random string
string.truncate
Truncate a string to a specified length.
Whether to complete words instead of cutting them off
Suffix to append when truncated
Returns: string
string.truncate('Hello world', 8) // 'Hello...'
string.truncate('Hello world', 8, { completeWords: true }) // 'Hello...'
string.excerpt
Create an excerpt from a longer text.
Maximum length of excerpt
Options for excerpt generation
Returns: string
const text = 'Lorem ipsum dolor sit amet'
string.excerpt(text, 15) // 'Lorem ipsum...'
string.slug
Generate a URL-friendly slug.
The string to convert to slug
Character to use as replacement
Returns: string
string.slug('Hello World!') // 'hello-world'
string.slug('Hello World!', { replacement: '_' }) // 'hello_world'
string.isEmpty
Check if a string is empty or contains only whitespace.
Returns: boolean
string.isEmpty('') // true
string.isEmpty(' ') // true
string.isEmpty('hello') // false
string.escapeHTML
Escape HTML entities to prevent XSS attacks.
Whether to encode Unicode symbols as HTML entities
Returns: string
string.escapeHTML('<script>alert("xss")</script>')
// '<script>alert("xss")</script>'
string.escapeHTML('© 2023', { encodeSymbols: true })
// '© 2023'
string.encodeSymbols
Encode Unicode symbols as HTML entities.
The string containing symbols to encode
Encoding options from the ‘he’ library
Returns: string
string.encodeSymbols('© 2023 AdonisJS ™')
// '© 2023 AdonisJS ™'
string.prettyHrTime
Convert high-resolution time to human-readable format.
High-resolution time tuple from process.hrtime()
Use verbose format (e.g., ‘1 second’ vs ‘1s’)
Show precise decimal places
Returns: string
const start = process.hrtime()
// ... some operation
const diff = process.hrtime(start)
string.prettyHrTime(diff) // '2.5ms'
string.prettyHrTime(diff, { verbose: true }) // '2 milliseconds'
string.create
Create a StringBuilder instance for efficient string concatenation.
value
string | StringBuilder
required
Initial string value or existing StringBuilder
Returns: StringBuilder
const builder = string.create('Hello')
builder.append(' ').append('World')
console.log(builder.toString()) // 'Hello World'
Assertion Utilities
Type-safe assertion functions for runtime checks.
import {
assertExists,
assertNotNull,
assertIsDefined,
assertUnreachable
} from '@adonisjs/core/helpers'
assertExists
Assert that a value exists (is not null or undefined).
value
T | null | undefined
required
The value to check
Throws: Error if value is null or undefined
function processUser(user: User | null) {
assertExists(user) // TypeScript knows user is not null after this
console.log(user.name) // Safe to access properties
}
assertNotNull
Assert that a value is not null.
Throws: Error if value is null
assertNotNull(userInput)
// TypeScript knows userInput is not null here
assertIsDefined
Assert that a value is defined (is not undefined).
Throws: Error if value is undefined
assertIsDefined(config.apiKey)
// TypeScript knows config.apiKey is defined here
assertUnreachable
Assert that code should never reach this point. Useful for exhaustiveness checking.
The value that should be of type never
Throws: Error always
function handleStatus(status: 'pending' | 'completed') {
switch (status) {
case 'pending':
return 'Processing...'
case 'completed':
return 'Done!'
default:
return assertUnreachable(status)
}
}
Type Checking Utilities
Comprehensive type checking with TypeScript type guards.
import { is } from '@adonisjs/core/helpers'
The is object provides numerous type-checking utilities re-exported from @sindresorhus/is. Here are some commonly used methods:
Basic Types
is.string(value) // Check if value is a string
is.number(value) // Check if value is a number
is.boolean(value) // Check if value is a boolean
is.array(value) // Check if value is an array
is.object(value) // Check if value is an object
is.function(value) // Check if value is a function
is.null(value) // Check if value is null
is.undefined(value) // Check if value is undefined
Advanced Types
is.plainObject(obj) // Check if object is plain (not class instance)
is.emptyObject(obj) // Check if object is empty
is.nonEmptyObject(obj) // Check if object has properties
is.emptyArray(arr) // Check if array is empty
is.nonEmptyArray(arr) // Check if array has elements
is.integer(num) // Check if number is integer
is.positiveNumber(num) // Check if number is positive
is.negativeNumber(num) // Check if number is negative
is.promise(value) // Check if value is a Promise
is.asyncFunction(fn) // Check if function is async
is.date(value) // Check if value is a Date
is.validDate(date) // Check if Date is valid
Usage Examples
if (is.string(value)) {
// TypeScript knows value is string
console.log(value.toUpperCase())
}
if (is.array(value) && is.nonEmptyArray(value)) {
console.log('Array has items:', value.length)
}
if (is.plainObject(obj) && is.hasProperty(obj, 'name')) {
console.log('Object has name property')
}
if (is.number(num) && is.integer(num) && is.positive(num)) {
console.log('Positive integer:', num)
}
HTTP Helpers
HTTP-related utilities are re-exported from @adonisjs/http-server/helpers.
import { middlewareInfo, routeInfo } from '@adonisjs/core/helpers/http'
For detailed documentation on HTTP helpers, refer to the HTTP Server documentation.
Utility Functions
defineStaticProperty
Define a static property on a class that is not enumerable.
The target object (usually a class)
The name of the property to define
The value of the property
import { defineStaticProperty } from '@adonisjs/core/helpers'
class MyClass {}
defineStaticProperty(MyClass, 'version', '1.0.0')
console.log(MyClass.version) // '1.0.0'