Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Configuration and environment variables

Application settings live in two places. Values that differ between your computer and the server (port, database password, keys) are in the .env file. Everything else is described in TypeScript files in the config/ folder.

The .env file

The .env file in the project root is created with the project:

TZ=UTC
PORT=3333
HOST=localhost
LOG_LEVEL=info
APP_KEY=x1yGq4VhT8sZ0cKfR2mN7pLw3bDe9uJa
NODE_ENV=development
SESSION_DRIVER=cookie

APP_KEY is the secret key used to encrypt cookies and sessions. To create a new key, run node ace generate:key.

Checks in start/env.ts

AdonisJS does not read .env blindly. The file start/env.ts lists every variable and its type:

// start/env.ts
import { Env } from '@adonisjs/core/env'
 
export default await Env.create(new URL('../', import.meta.url), {
  NODE_ENV: Env.schema.enum(['development', 'production', 'test'] as const),
  PORT: Env.schema.number(),
  APP_KEY: Env.schema.string(),
  HOST: Env.schema.string({ format: 'host' }),
  LOG_LEVEL: Env.schema.string(),
  SESSION_DRIVER: Env.schema.enum(['cookie', 'memory'] as const),
})

On startup the application checks every variable. If PORT is not a number or APP_KEY is missing, the server does not start and the terminal says which variable is wrong.

Your own variable

Let us add the number of posts per page to the blog. First a line in .env:

POSTS_PER_PAGE=10

Then a description in start/env.ts, inside the same object:

// start/env.ts
POSTS_PER_PAGE: Env.schema.number.optional(),

optional() allows the variable to be missing. You can read the value in any file:

// app/controllers/posts_controller.ts
import env from '#start/env'
 
const perPage = env.get('POSTS_PER_PAGE', 10)

The second argument of get is the default value. TypeScript knows the result type from the schema: here it is number.

The config folder

Each package keeps its settings in its own file: config/app.ts, config/database.ts, config/session.ts. You can move your own settings into a separate file as well:

// config/blog.ts
import env from '#start/env'
 
const blogConfig = {
  title: 'My blog',
  postsPerPage: env.get('POSTS_PER_PAGE', 10),
}
 
export default blogConfig
// app/controllers/posts_controller.ts
import blogConfig from '#config/blog'
 
console.log(blogConfig.title)

A config file is an ordinary module, so you import it like any other.

Common mistake

The variable was added to .env but not described in start/env.ts. Then env.get('POSTS_PER_PAGE') shows a type error in the editor, and the value is not checked. Write every new variable into both files. And do not commit .env to Git: it holds secrets, and on the server it is created separately.

Thanks for reading!

Donate to the site — we work hard for you.