### Environment-Specific Actions in Service Provider
Source: https://v6-docs.adonisjs.com/guides/concepts/service-providers
The `start` method is used to perform actions based on the application's current environment. This example includes conditional logic for 'web', 'console', 'test', and 'repl' environments.
```typescript
export default class AppProvider {
async start() {
if (this.app.getEnvironment() === 'web') {
}
if (this.app.getEnvironment() === 'console') {
}
if (this.app.getEnvironment() === 'test') {
}
if (this.app.getEnvironment() === 'repl') {
}
}
}
```
--------------------------------
### Install Basic Auth Guard Package
Source: https://v6-docs.adonisjs.com/guides/authentication/introduction
Installs the @adonisjs/auth package with the basic_auth guard using the AdonisJS CLI. This command automatically handles the initial setup steps.
```bash
node ace add @adonisjs/auth --guard=basic_auth
```
--------------------------------
### Create New AdonisJS Application
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Initializes a new AdonisJS project named 'hello-world' using the latest version of the create-adonisjs package via npm. This is the basic command to start a new project.
```bash
npm init adonisjs@latest hello-world
```
--------------------------------
### Manage Development and Production Processes
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Commands to start the development server with hot module replacement and to compile the TypeScript application for production deployment.
```bash
node ace serve --hmr
node ace build
```
--------------------------------
### Initialize AdonisJS Projects with Starter Kits
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Commands to scaffold new AdonisJS applications using different starter kits like API, Slim, and Inertia. These commands support flags for database selection, authentication guards, and frontend adapters.
```bash
npm init adonisjs@latest -- -K=api --db=mysql
npm init adonisjs@latest -- -K=api --auth-guard=access_tokens
npm init adonisjs@latest -- -K=slim
npm init adonisjs@latest -- -K=slim --db=mysql
npm init adonisjs@latest -- -K=inertia
npm init adonisjs@latest -- -K=inertia --adapter=react --ssr
npm init adonisjs@latest -- -K=inertia --adapter=vue --no-ssr
```
--------------------------------
### Install Prettier Configuration Preset
Source: https://v6-docs.adonisjs.com/guides/concepts/tooling-config
Install the base Prettier configuration preset for auto-formatting source code. Also, install the Prettier package itself.
```bash
npm i -D @adonisjs/prettier-config
# Make sure also to install prettier
npm i -D prettier
```
--------------------------------
### Create AdonisJS App with Customizations (npm init)
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Demonstrates creating a new AdonisJS project with specific configurations using npm init. It shows how to pass CLI flags like database dialect (--db) and starter kit (--kit) to the create-adonisjs initializer.
```bash
# Create a project and get prompted for all options
npm init adonisjs@latest hello-world
# Create a project with MySQL
npm init adonisjs@latest hello-world -- --db=mysql
# Create a project with PostgreSQL and API starter kit
npm init adonisjs@latest hello-world -- --db=postgres --kit=api
# Create a project with API starter kit and access tokens guard
npm init adonisjs@latest hello-world -- --kit=api --auth-guard=access_tokens
```
--------------------------------
### Create Web Starter Kit Application (AdonisJS)
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Initializes a new AdonisJS project using the 'web' starter kit. This kit is suitable for traditional server-rendered web applications and uses Edge.js for templating. It also shows how to specify a database dialect.
```bash
npm init adonisjs@latest -- -K=web
# Switch database dialect
npm init adonisjs@latest -- -K=web --db=mysql
```
--------------------------------
### Install BullMQ for Email Queueing
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/mail
Install the `bullmq` package to use it as a robust queue for sending emails in the background.
```bash
npm i bullmq
```
--------------------------------
### Install ESLint Configuration Preset
Source: https://v6-docs.adonisjs.com/guides/concepts/tooling-config
Install the base ESLint configuration preset for applying linting rules. Ensure you also install the ESLint package.
```bash
npm i -D @adonisjs/eslint-config
# Make sure also to install eslint
npm i -D eslint
```
--------------------------------
### Import Custom Starter Kits from Repositories
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Commands to initialize an AdonisJS project from external Git repositories including GitHub, GitLab, and Bitbucket. Supports specifying branches, tags, or commits and using SSH mode for private repositories.
```bash
npm init adonisjs@latest -- -K="github_user/repo"
npm init adonisjs@latest -- -K="gitlab:user/repo"
npm init adonisjs@latest -- -K="bitbucket:user/repo"
npm init adonisjs@latest -- -K="user/repo" --mode=git
npm init adonisjs@latest -- -K="user/repo#develop"
npm init adonisjs@latest -- -K="user/repo#v2.1.0"
```
--------------------------------
### Create API Starter Kit Application (AdonisJS)
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Initializes a new AdonisJS project using the 'api' starter kit. This kit is optimized for building JSON API servers and is a trimmed-down version of the web starter kit, ideal for use with frontend frameworks like React or Vue.
```bash
npm init adonisjs@latest -- -K=api
```
--------------------------------
### Install and Configure Inertia in AdonisJS
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
Commands and configuration snippets to install the Inertia package and register the necessary providers and middleware.
```bash
npm i @adonisjs/inertia
node ace configure @adonisjs/inertia
```
```typescript
providers: [
// ...other providers
() => import('@adonisjs/inertia/inertia_provider')
]
```
```typescript
router.use([() => import('@adonisjs/inertia/inertia_middleware')])
```
--------------------------------
### Add Development Dependency and Configure
Source: https://v6-docs.adonisjs.com/guides/references/commands
Installs a package as a development dependency and configures it.
```bash
node ace add my-dev-package --dev
```
--------------------------------
### AdonisJS Start Directory Structure
Source: https://v6-docs.adonisjs.com/guides/getting-started/folder-structure
Outlines the default files within the `start` directory, used for organizing code that needs to be imported during the application's boot lifecycle, such as route definitions and event listeners.
```bash
├── start
│ ├── env.ts
│ ├── kernel.ts
│ ├── routes.ts
│ ├── validator.ts
│ └── events.ts
```
--------------------------------
### Install jsonwebtoken Package
Source: https://v6-docs.adonisjs.com/guides/authentication/custom-auth-guard
Installs the necessary jsonwebtoken package and its types for generating JWT tokens.
```bash
npm i jsonwebtoken @types/jsonwebtoken
```
--------------------------------
### Start Production Server with Custom .env Path
Source: https://v6-docs.adonisjs.com/guides/getting-started/deployment
When deploying on a bare-bone server, use an .env file for environment variables. This command starts the production server, instructing AdonisJS to look for the .env file in a specified directory.
```bash
ENV_PATH=/etc/secrets node build/bin/server.js
```
--------------------------------
### Start AdonisJS REPL
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/repl
Initiate an AdonisJS REPL session to interact with your application. This command starts the interactive environment.
```bash
node ace repl
```
--------------------------------
### Add and Configure Package
Source: https://v6-docs.adonisjs.com/guides/references/commands
Installs a package using the application's detected package manager and then configures it. This combines `npm install` and `node ace configure`.
```bash
node ace add @adonisjs/lucid
```
--------------------------------
### Registering Environment-Specific Service Providers
Source: https://v6-docs.adonisjs.com/guides/concepts/service-providers
This example demonstrates how to register a service provider for specific runtime environments like 'web' or 'repl'. The `file` property points to the provider, and `environment` specifies when it should load.
```typescript
{
providers: [
() => import('@adonisjs/core/providers/app_provider'),
{
file: () => import('./providers/app_provider.js'),
environment: ['web', 'repl']
}
]
}
```
--------------------------------
### Install @adonisjs/drive Package
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/drive
Install the Drive package using the Ace command. This command also registers the service provider and creates configuration files.
```bash
node ace add @adonisjs/drive
```
--------------------------------
### Configure a Package
Source: https://v6-docs.adonisjs.com/guides/references/commands
Use this command to configure a package after installation. It takes the package name as an argument. The --verbose flag shows installation logs, and --force overwrites existing files.
```bash
node ace configure @adonisjs/lucid
```
--------------------------------
### Create Limiter Instance with Redis Store
Source: https://v6-docs.adonisjs.com/guides/security/rate-limiting
Get an instance of the Limiter class using `limiter.use` to apply rate limits directly within your application logic. This example uses the Redis store.
```typescript
import limiter from '@adonisjs/limiter/services/main'
const reportsLimiter = limiter.use('redis', {
requests: 1,
duration: '1 hour'
})
```
--------------------------------
### Install @adonisjs/limiter Package
Source: https://v6-docs.adonisjs.com/guides/security/rate-limiting
Install the rate limiting package using the AdonisJS CLI. This command also registers the service provider and creates necessary configuration files.
```bash
node ace add @adonisjs/limiter
```
--------------------------------
### AdonisJS Ace Command with startApp enabled
Source: https://v6-docs.adonisjs.com/guides/concepts/application-lifecycle
This example demonstrates an AdonisJS Ace command that enables the `startApp` option. This ensures that the application is fully booted and ready before the command's `run` method is executed. It logs the application's ready state to the console.
```typescript
import { BaseCommand } from '@adonisjs/core/ace'
export default class GreetCommand extends BaseCommand {
static options = {
startApp: true
}
async run() {
console.log(this.app.isReady) // true
}
}
```
--------------------------------
### Install @adonisjs/cache Package
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/cache
Install the cache package using the Ace command. This command also registers the service provider and creates the configuration file.
```bash
node ace add @adonisjs/cache
```
--------------------------------
### Install Bcrypt Driver
Source: https://v6-docs.adonisjs.com/guides/security/hashing
Install the bcrypt npm package to use it with the AdonisJS hash service.
```bash
npm i bcrypt
```
--------------------------------
### Install Argon2 Package
Source: https://v6-docs.adonisjs.com/guides/security/hashing
To use the Argon2 hashing algorithm, you must first install the `argon2` npm package.
```bash
npm i argon2
```
--------------------------------
### Create a new preload file
Source: https://v6-docs.adonisjs.com/guides/references/commands
Generate a new preload file, which is stored in the `start` directory. Preload files are executed when the application starts.
```bash
node ace make:preload view
```
--------------------------------
### Install MJML Package
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/mail
Install the MJML package using npm to enable MJML markup for responsive email design.
```bash
npm i mjml
```
--------------------------------
### Install API Client Plugin
Source: https://v6-docs.adonisjs.com/guides/testing/http-tests
Install the Japa API client plugin to enable making HTTP requests within your tests. This is a development dependency.
```bash
npm i -D @japa/api-client
```
--------------------------------
### Serve Application with Asset Bundler Args
Source: https://v6-docs.adonisjs.com/guides/references/commands
Starts the development server and passes specific arguments to the asset bundler development server.
```bash
node ace serve --hmr --assets-args="--cors --open"
```
--------------------------------
### Install AdonisJS i18n Package
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/i18n
Installs the `@adonisjs/i18n` package and registers its service provider. This command automatically handles package installation and configuration file setup.
```bash
node ace add @adonisjs/i18n
```
--------------------------------
### Configure command to start application
Source: https://v6-docs.adonisjs.com/guides/ace/creating-commands
Set `options.startApp` to `true` if your command requires the application to be booted before execution.
```typescript
import { BaseCommand } from '@adonisjs/core/ace'
import { CommandOptions } from '@adonisjs/core/types/ace'
export default class GreetCommand extends BaseCommand {
static options: CommandOptions = {
startApp: true
}
}
```
--------------------------------
### Install TypeScript Configuration Preset
Source: https://v6-docs.adonisjs.com/guides/concepts/tooling-config
Install the base TypeScript configuration preset for AdonisJS projects. Ensure you also install the necessary TypeScript and SWC packages.
```bash
npm i -D @adonisjs/tsconfig
# Make sure also to install the following packages
npm i -D typescript ts-node-maintained @swc/core
```
--------------------------------
### Install pino-roll for File Rotation
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/logger
Install the `pino-roll` package to handle log file rotation, as Pino does not include this functionality by default. This is an alternative to system-level tools like logrotate.
```bash
npm i pino-roll
```
--------------------------------
### Install Nodemailer Postmark Transport
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/mail
Install the necessary npm packages for integrating the Postmark transport with Nodemailer.
```bash
npm i nodemailer nodemailer-postmark-transport
```
--------------------------------
### Manually Define Inertia Page Props in Vue 3 Script Setup
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
This example addresses a limitation in Vue where `defineProps` requires explicit declaration of each prop, even when using `InferPageProps` for type inference. It shows how to extract specific prop types from `InferPageProps` to manually define them within a Vue 3 `
```
--------------------------------
### Install with specific transports
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/mail
Installs the @adonisjs/mail package and pre-defines transports to use via CLI flag.
```bash
node ace add @adonisjs/mail --transports=resend --transports=smtp
```
--------------------------------
### Install Playwright and Japa Browser Client
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
Installs the necessary Playwright and @japa/browser-client packages as development dependencies using npm.
```bash
npm i -D playwright @japa/browser-client
```
--------------------------------
### Verify Node.js Version
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
This command checks the installed Node.js version. AdonisJS requires Node.js version 20 or higher. Ensure your Node.js installation meets this requirement before proceeding.
```bash
node -v
```
--------------------------------
### Serve Application with Node Arguments
Source: https://v6-docs.adonisjs.com/guides/references/commands
Passes Node.js arguments like --no-warnings and --inspect to the child process when starting the development server.
```bash
node ace --no-warnings --inspect serve --hmr
```
--------------------------------
### Install @adonisjs/lock Package
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/locks
Install the @adonisjs/lock package using the Ace command. This command also registers the service provider and creates necessary configuration files.
```bash
node ace add @adonisjs/lock
```
--------------------------------
### Install and Configure AdonisJS Ally
Source: https://v6-docs.adonisjs.com/guides/authentication/social-authentication
Commands to install the Ally package and register providers via the AdonisJS CLI.
```bash
node ace add @adonisjs/ally
node ace add @adonisjs/ally --providers=github --providers=google
```
--------------------------------
### Install VineJS Validator Package
Source: https://v6-docs.adonisjs.com/guides/basics/validation
Installs the VineJS package and registers its service provider in the AdonisJS application. This command automates the setup process for data validation.
```bash
node ace add vinejs
```
--------------------------------
### Install and Configure @adonisjs/vite
Source: https://v6-docs.adonisjs.com/guides/basics/vite
Installs the @adonisjs/vite package and Vite itself, then configures the project by creating necessary files and registering the service provider. This command automates the initial setup for integrating Vite with AdonisJS.
```bash
node ace add @adonisjs/vite
```
--------------------------------
### Execute Custom REPL Method
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/repl
Start the REPL session and execute the custom 'loadModels' method to import models. Use '.ls' to view available context methods and properties.
```bash
node ace repl
# Type ".ls" to a view list of available context methods/properties
> (js) await loadModels()
```
--------------------------------
### GET /posts/:id
Source: https://v6-docs.adonisjs.com/guides/basics/routing
Retrieves a post by ID with global and local route matching constraints.
```APIDOC
## GET /posts/:id
### Description
Retrieves a specific post. Uses a global UUID matcher by default, which can be overridden at the route level.
### Method
GET
### Endpoint
/posts/:id
### Parameters
#### Path Parameters
- **id** (string/number) - Required - The unique identifier of the post.
### Response
#### Success Response (200)
- **post** (object) - The post details.
#### Response Example
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"title": "My First Post"
}
```
--------------------------------
### Start Server with PM2
Source: https://v6-docs.adonisjs.com/guides/getting-started/deployment
Use PM2 to start your AdonisJS application using the defined ecosystem file. PM2 manages the application in the background, handles restarts, and supports cluster mode.
```bash
pm2 start ecosystem.config.js
```
--------------------------------
### Basic Browser Test Example
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
An example of a basic browser test using Japa. This test visits the root URL ('/') and asserts that the text 'It works!' is present in the 'body' element of the page.
```typescript
import { test } from '@japa/runner'
test.group('Home page', () => {
test('see welcome message', async ({ visit }) => {
const page = await visit('/')
await page.assertTextContains('body', 'It works!')
})
})
```
--------------------------------
### Setup raw mode for Ace command testing
Source: https://v6-docs.adonisjs.com/guides/testing/console-tests
Use the 'each.setup' hook to switch Ace's UI mode to 'raw' before tests run and back to 'normal' afterwards. This prevents logs from appearing in the terminal and stores them in memory for assertions.
```typescript
test.group('Commands greet', (group) => {
group.each.setup(() => {
ace.ui.switchMode('raw')
return () => ace.ui.switchMode('normal')
})
// test goes here
})
```
--------------------------------
### Define Controller Class
Source: https://v6-docs.adonisjs.com/guides/basics/controllers
Example of a standard controller class with an index method that returns user data.
```typescript
export default class UsersController {
index() {
return [
{
id: 1,
username: 'virk',
},
{
id: 2,
username: 'romain',
},
]
}
}
```
--------------------------------
### Run Production Build
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
Demonstrates the command to run the production server with the correct environment variable to avoid build errors.
```bash
NODE_ENV=production node build/server.js
```
--------------------------------
### Handle Complex Route Parameters
Source: https://v6-docs.adonisjs.com/guides/basics/routing
Examples of handling multiple parameters, optional parameters, and wildcard segments in route definitions.
```TypeScript
import router from '@adonisjs/core/services/router'
// Multiple params
router.get('/posts/:id/comments/:commentId', ({ params }) => {
console.log(params.id)
console.log(params.commentId)
})
// Optional params
router.get('/posts/:id?', ({ params }) => {
if (!params.id) return 'Showing all posts'
return `Showing post with id ${params.id}`
})
// Wildcard params
router.get('/docs/:category/*', ({ params }) => {
console.log(params.category)
console.log(params['*'])
})
```
--------------------------------
### Configure Transmit Server
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/transmit
Configuration examples for the Transmit service, including basic settings and Redis transport setup for multi-server synchronization.
```typescript
import { defineConfig } from '@adonisjs/transmit'
export default defineConfig({
pingInterval: false,
transport: null,
})
```
```typescript
import env from '#start/env'
import { defineConfig } from '@adonisjs/transmit'
import { redis } from '@adonisjs/transmit/transports'
export default defineConfig({
transport: {
driver: redis({
host: env.get('REDIS_HOST'),
port: env.get('REDIS_PORT'),
password: env.get('REDIS_PASSWORD'),
keyPrefix: 'transmit',
})
}
})
```
--------------------------------
### Set Server-Side Cookie
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
An example of setting a cookie on the server response within a route handler. This cookie can then be accessed by the browser test.
```typescript
import router from '@adonisjs/core/services/router'
router.get('/', async ({ response }) => {
response.cookie('cartTotal', '100')
return 'It works!'
})
```
--------------------------------
### Nginx Reverse Proxy Configuration
Source: https://v6-docs.adonisjs.com/guides/getting-started/deployment
An example Nginx configuration file to use as a starting point for proxying traffic to your AdonisJS application. Replace placeholders like and .
```nginx
server {
listen 80;
listen [::]:80;
server_name ;
location / {
proxy_pass http://localhost:;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}
```
--------------------------------
### Configure i18n Ally for AdonisJS
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/i18n
Setup commands and configuration files required to integrate the i18n Ally extension with an AdonisJS project structure.
```bash
mkdir .vscode
touch .vscode/i18n-ally-custom-framework.yml
touch .vscode/settings.json
```
```json
{
"i18n-ally.localesPaths": [
"resources/lang"
],
"i18n-ally.keystyle": "nested",
"i18n-ally.namespace": true,
"i18n-ally.editor.preferEditor": true,
"i18n-ally.refactor.templates": [
{
"templates": [
"{{ t('{key}'{args}) }}"
],
"include": [
"**/*.edge"
]
}
]
}
```
```yaml
languageIds:
- edge
usageMatchRegex:
- "[^\\w\\d]t\\(['\"`]({key})['\"`]"
sortKeys: true
```
--------------------------------
### Create events preload file
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/emitter
Use the `make:preload` ace command to create the `start/events.ts` file where event listeners are defined.
```bash
node ace make:preload events
```
--------------------------------
### Format plurals and lists with AdonisJS I18n
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/i18n
Provides examples for determining plural categories for numbers and joining arrays of strings into localized sentences.
```typescript
import i18nManager from '@adonisjs/i18n/services/main'
i18nManager.i18nManager('en').formatPlural(1)
i18nManager
.locale('en')
.formatList(['Me', 'myself', 'I'], { type: 'conjunction' })
```
--------------------------------
### Create Inertia Frontend Component with Vue.js
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
A Vue.js component example showing how to receive props from an Inertia controller and use the Link component for navigation.
```vue
{{ user.name }}
{{ user.email }}
```
--------------------------------
### List Available Helper Methods in REPL
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/repl
Execute the `.ls` command in the REPL to view a list of all available global helper methods and their descriptions. This command helps in discovering and utilizing built-in utilities.
```bash
> (js) .ls
# GLOBAL METHODS:
importDefault Returns the default export for a module
make Make class instance using "container.make" method
loadApp Load "app" service in the REPL context
loadEncryption Load "encryption" service in the REPL context
loadHash Load "hash" service in the REPL context
loadRouter Load "router" service in the REPL context
loadConfig Load "config" service in the REPL context
loadTestUtils Load "testUtils" service in the REPL context
loadHelpers Load "helpers" module in the REPL context
clear Clear a property from the REPL context
p Promisify a function. Similar to Node.js "util.promisify"
```
--------------------------------
### Add and Configure Package with Flags
Source: https://v6-docs.adonisjs.com/guides/references/commands
Installs and configures a package, passing specific flags to the configure command. Unknown flags are passed down to the configure command.
```bash
node ace add @adonisjs/lucid --db=sqlite
```
--------------------------------
### Read/Write Encrypted and Plain Cookies
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
Provides examples of using 'setEncryptedCookie', 'setPlainCookie', 'getEncryptedCookie', and 'getPlainCookie' methods on the browserContext to manage different types of cookies.
```typescript
// Write
await browserContext.setEncryptedCookie('username', 'virk')
await browserContext.setPlainCookie('username', 'virk')
// Read
await browserContext.getEncryptedCookie('cartTotal')
await browserContext.getPlainCookie('cartTotal')
```
--------------------------------
### Run Code Quality Tools
Source: https://v6-docs.adonisjs.com/guides/getting-started/installation
Commands to execute ESLint for linting and auto-fixing code issues, and Prettier for formatting code according to project standards.
```bash
npm run lint
npm run lint -- --fix
npm run format
```
--------------------------------
### Build Application with Asset Bundler Args
Source: https://v6-docs.adonisjs.com/guides/references/commands
Builds the production application and passes specific arguments to the asset bundler process.
```bash
node ace build --assets-args="--sourcemap --debug"
```
--------------------------------
### Register HTTP Method Routes
Source: https://v6-docs.adonisjs.com/guides/basics/routing
Shows how to register routes for standard HTTP verbs (GET, POST, PUT, PATCH, DELETE), handle all methods, or define custom methods.
```TypeScript
import router from '@adonisjs/core/services/router'
// Standard methods
router.get('users', () => {})
router.post('users', () => {})
router.put('users/:id', () => {})
router.patch('users/:id', () => {})
router.delete('users/:id', () => {})
// All methods
router.any('reports', () => {})
// Custom methods
router.route('/', ['TRACE'], () => {})
```
--------------------------------
### Get Server-Set Cookie in Test
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
Shows how to retrieve a cookie set by the server within a browser test. The 'browserContext.getCookie' method is used to access cookies persisted in the browser context.
```typescript
test.group('Home page', () => {
test('see welcome message', async ({ visit, browserContext }) => {
const page = await visit('/')
console.log(await browserContext.getCookie('cartTotal'))
})
})
```
--------------------------------
### Providers Directory Structure
Source: https://v6-docs.adonisjs.com/guides/getting-started/folder-structure
Stores application service providers. Use `node ace make:provider` to create new ones.
```bash
├── providers
│ └── app_provider.ts
│ └── http_server_provider.ts
```
--------------------------------
### Define Assembler Hooks in adonisrc.ts
Source: https://v6-docs.adonisjs.com/guides/concepts/assembler-hooks
This snippet shows how to define various Assembler hooks within the `adonisrc.ts` configuration file. It demonstrates using dynamic imports for each hook to ensure they are loaded only when needed, preventing unnecessary performance impact. The hooks cover build start, build completion, dev server start, and source file changes.
```typescript
import { defineConfig } from '@adonisjs/core/app'
export default defineConfig({
hooks: {
onBuildCompleted: [
() => import('my-package/hooks/on_build_completed')
],
onBuildStarting: [
() => import('my-package/hooks/on_build_starting')
],
onDevServerStarted: [
() => import('my-package/hooks/on_dev_server_started')
],
onSourceFileChanged: [
() => import('my-package/hooks/on_source_file_changed')
],
},
})
```
--------------------------------
### SSR Allowlist Configuration (Specific Pages)
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
This code snippet illustrates how to configure an SSR allowlist in `config/inertia.ts` for specific pages that should be server-side rendered. In this example, only the 'home' page is included in the allowlist.
```typescript
import { defineConfig } from '@adonisjs/inertia'
export default defineConfig({
ssr: {
enabled: true,
pages: ['home']
}
})
```
--------------------------------
### Setup Session Browser Client in AdonisJS Tests
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
Registers the session browser client plugin in the tests/bootstrap.ts file to enable session management in browser tests. Requires the @adonisjs.session/plugins/browser_client package.
```typescript
import { sessionBrowserClient } from '@adonisjs/session/plugins/browser_client'
export const plugins: Config['plugins'] = [
assert(),
pluginAdonisJS(app),
sessionBrowserClient(app)
]
```
--------------------------------
### ICU message interpolation
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/i18n
Shows how to define dynamic values in translation files using curly braces and render them in Edge templates. Includes examples for both standard text and HTML content.
```json
{
"greeting": "Hello { username }"
}
```
```edge
{{ t('messages.greeting', { username: 'Virk' }) }}
```
```json
{
"greeting": "
Hello { username }
"
}
```
```edge
{{{ t('messages.greeting', { username: 'Virk' }) }}}
```
--------------------------------
### Define command help text
Source: https://v6-docs.adonisjs.com/guides/ace/creating-commands
Provide detailed help text, including usage examples, using the static `help` property. The `{{ binaryName }}` variable is substituted with the Ace binary name.
```typescript
export default class GreetCommand extends BaseCommand {
static help = [
'The greet command is used to greet a user by name',
'',
'You can also send flowers to a user, if they have an updated address',
'{{ binaryName }} greet --send-flowers',
]
}
```
--------------------------------
### Handle Redirects with AdonisJS and Inertia
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
This controller example demonstrates two ways to handle redirects in AdonisJS with Inertia.js. Standard AdonisJS redirects use `response.redirect().toRoute()`, while external redirects can be handled using `inertia.location()`.
```typescript
export default class UsersController {
async store({ response }: HttpContext) {
await User.create(request.body())
// 👇 You can use standard AdonisJS redirections
return response.redirect().toRoute('users.index')
}
async externalRedirect({ inertia }: HttpContext) {
// 👇 Or use the inertia.location for external redirects
return inertia.location('https://adonisjs.com')
}
}
```
--------------------------------
### Creating a Middleware File
Source: https://v6-docs.adonisjs.com/guides/basics/middleware
Generate a new middleware file using the `make:middleware` Ace command. This creates a boilerplate middleware class in the `./app/middleware` directory.
```bash
node ace make:middleware user_location
```
--------------------------------
### Extend Router classes with macros and getters
Source: https://v6-docs.adonisjs.com/guides/basics/routing
Provides examples of extending core AdonisJS router classes (Router, Route, RouteGroup, RouteResource, BriskRoute) using macros and getters, including the necessary TypeScript declaration merging.
```typescript
import { Router } from '@adonisjs/core/http'
Router.macro('property', function (this: Router) { return value })
Router.getter('propertyName', function (this: Router) { return value })
// In types/http.ts
declare module '@adonisjs/core/http' {
export interface Router { property: valueType }
}
```
--------------------------------
### Configure Fallback Locales for i18n
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/i18n
Defines fallback locales for the i18n configuration. This allows specifying a default language to use when a translation for a specific user locale is not available. For example, Spanish is set as a fallback for Catalan.
```typescript
export default defineConfig({
formatter: formatters.icu(),
defaultLocale: 'en',
fallbackLocales: {
ca: 'es' // show Spanish content when a user speaks Catalan
}
})
```
--------------------------------
### Initialize Node.js Project
Source: https://v6-docs.adonisjs.com/guides/concepts/async-local-storage
Initializes a new Node.js project using npm and configures it to use the ES Module system by setting the 'type' to 'module' in package.json.
```bash
npm init --yes
```
```json
{
"type": "module"
}
```
--------------------------------
### Extending Validator Bindings in Service Provider
Source: https://v6-docs.adonisjs.com/guides/concepts/service-providers
This `boot` method example shows how to extend the 'validator' binding. It uses the `resolving` hook to add a custom validation rule named 'foo' after the validator has been resolved from the container.
```typescript
async boot() {
this.app.container.resolving('validator', (validator) => {
validator.rule('foo', () => {})
})
}
```
--------------------------------
### Run Database Migrations in Production
Source: https://v6-docs.adonisjs.com/guides/getting-started/deployment
Execute database migrations on the production server to create necessary tables. The --force flag is required when running migrations in a production environment.
```bash
node ace migration:run --force
```
--------------------------------
### Service Provider Lifecycle Methods
Source: https://v6-docs.adonisjs.com/guides/concepts/service-providers
This snippet outlines the available lifecycle methods for an AdonisJS service provider: `register`, `boot`, `start`, `ready`, and `shutdown`. These methods allow you to hook into different stages of the application's lifecycle.
```typescript
export default class AppProvider {
register() {
}
async boot() {
}
async start() {
}
async ready() {
}
async shutdown() {
}
}
```
--------------------------------
### Import and Use Drive Service
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/drive
Import the Drive service singleton to interact with configured file storage. Use `drive.use()` to get an instance of the default disk or a named disk.
```typescript
import drive from '@adonisjs/drive/services/main'
drive instanceof DriveManager // true
/**
* Returns instance of the default disk
*/
const disk = drive.use()
/**
* Returns instance of a disk named r2
*/
const disk = drive.use('r2')
/**
* Returns instance of a disk named spaces
*/
const disk = drive.use('spaces')
```
--------------------------------
### AdonisJS Service Provider Lifecycle Hooks
Source: https://v6-docs.adonisjs.com/guides/concepts/application-lifecycle
Illustrates defining lifecycle hooks as methods within a service provider class. This approach is recommended for better organization, allowing actions during registration, booting, starting, readiness, and shutdown.
```typescript
import { ApplicationService } from '@adonisjs/core/types'
export default class AppProvider {
constructor(protected app: ApplicationService) {}
register() {
}
async boot() {
}
async start() {
}
async ready() {
}
async shutdown() {
}
}
```
--------------------------------
### Create .prettierignore file
Source: https://v6-docs.adonisjs.com/guides/concepts/tooling-config
Create a .prettierignore file to specify files and directories that Prettier should ignore during formatting.
```ignore
build
node_modules
```
--------------------------------
### Setup Auth Browser Client in AdonisJS Tests
Source: https://v6-docs.adonisjs.com/guides/testing/browser-tests
Registers the auth browser client plugin in tests/bootstrap.ts to facilitate user authentication in browser tests using the @adonisjs.auth/plugins/browser_client package. Ensure session plugin is also set up for session-based authentication.
```typescript
import { authBrowserClient } from '@adonisjs/auth/plugins/browser_client'
export const plugins: Config['plugins'] = [
assert(),
pluginAdonisJS(app),
authBrowserClient(app)
]
```
--------------------------------
### Database Directory Structure
Source: https://v6-docs.adonisjs.com/guides/getting-started/folder-structure
Contains database migrations and seeders.
```bash
├── database
│ └── migrations
│ └── seeders
```
--------------------------------
### Production Environment Variables Configuration
Source: https://v6-docs.adonisjs.com/guides/getting-started/environment-variables
Recommends using deployment platform's built-in support for environment variables. Provides fallback using `.env` file and `ENV_PATH`.
```bash
# Attempts to read .env file from project root
node server.js
# Reads the .env file from the "/etc/secrets" directory
ENV_PATH=/etc/secrets node server.js
```
--------------------------------
### Register Custom Hook in adonisrc.ts
Source: https://v6-docs.adonisjs.com/guides/concepts/assembler-hooks
This snippet shows how to register a custom hook, defined in a separate file (e.g., `./hooks/on_build_starting`), into the `adonisrc.ts` configuration. This allows the custom logic to be executed automatically when the corresponding Assembler event is triggered, such as before the build process starts.
```typescript
import { defineConfig } from '@adonisjs/core/app'
export default defineConfig({
hooks: {
onBuildStarting: [
() => import('./hooks/on_build_starting')
],
},
})
```
--------------------------------
### Configure Health Checks
Source: https://v6-docs.adonisjs.com/guides/digging-deeper/health-checks
Run this command to create the `start/health.ts` file and configure default health checks for memory and disk space.
```bash
node ace configure health_checks
```
--------------------------------
### Share Root Template Data in AdonisJS Controller
Source: https://v6-docs.adonisjs.com/guides/views-and-templates/inertia
This controller example shows how to pass data to the root Edge template when rendering a page. The third argument to `inertia.render` is an object containing data like 'title' and 'description', which can then be accessed within the root template.
```typescript
export default class PostsController {
async index({ inertia }: HttpContext) {
return inertia.render('posts/details', post, {
title: post.title,
description: post.description
})
}
}
```