Drizzle createdAt and updatedAt timestamps
Set Drizzle createdAt and updatedAt columns in NestJS. The package stamps them on every write, or the database owns them with defaultNow.
Drizzle createdAt and updatedAt columns in NestJS can be set two ways. By default the package stamps them itself: create writes both, and update, softDelete and restore move updated_at, all with the application clock. Or you turn package timestamps off and let the database own them with defaultNow(), $onUpdate() or a trigger. Pick one per entity; the database is the more reliable source of time.
The settings name keys, not SQL columns
timestamps.createdAt and timestamps.updatedAt are keys in your Drizzle table object,
created_at and updated_at by default. A camelCase schema needs them set, and since 3.3.1 a key
the table does not have stops the service at startup.
What does the package write, and when?
The package writes a JavaScript new Date() into the configured keys on writes that go through the
service:
| Operation | created_at | updated_at |
|---|---|---|
create, massCreate | Set to now | Set to now |
update, massUpdate | Left alone | Set to now |
softDelete, massSoftDelete, restore, massRestore | Left alone | Set to now |
upsert, massUpsert (insert) | Set to now | Set to now |
upsert, massUpsert (conflict, row updated) | Kept from the existing row | Set to now |
delete, forceDelete | (row removed) | (row removed) |
Two more rules keep the values honest:
- The body cannot override them. On create, the package writes both keys after mapping the
body, so a client-sent
created_atis replaced. On update,created_atis dropped from the body (unlesswritableColumnsnames it), so a row cannot move its creation date by accident. - An empty update is a 400.
update()with no column to change throwsValidationFailedException. It does not bumpupdated_aton its own.
defaults.timestampsOptionalboolean
Defaults to true
timestamps.createdAtOptionalstring
Defaults to "created_at"
timestamps.updatedAtOptionalstring
Defaults to "updated_at"
defaults.sortOrderOptional"asc" | "desc"
How do I set it up with package-managed timestamps?
Add the columns to the schema
import { pgTable, serial, timestamp, varchar } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 100 }).notNull(),
created_at: timestamp('created_at', { withTimezone: true }).notNull(),
updated_at: timestamp('updated_at', { withTimezone: true }).notNull(),
});Leave the project default on
DrizzleCrudModule.forRoot({
dialect: 'postgresql',
connectionString: process.env.DATABASE_URL,
schema,
defaults: { timestamps: true }, // the default
});Point camelCase keys at the right columns
With keys like createdAt: timestamp('created_at'), tell the entity which keys to use:
DrizzleCrudModule.forFeature([
{
service: UsersService,
table: users,
config: { timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } },
},
])The entity setting merges with the project default one level deep, so naming only updatedAt
keeps the default createdAt.
Why does my service fail at startup with a timestamps error?
Because a configured key is not on the table. Before 3.3.1 the package wrote updated_at into the
values, Drizzle ignored the unknown key, and updatedAt silently never moved. The service now checks
both keys when it is built and stops with a message that names the key to use when the column exists
under another name.
Fix it one of three ways:
- Set the keys, as in the step above.
- Turn timestamps off for that entity with
config: { timestamps: undefined }. - Turn them off for the project with
defaults: { timestamps: false }.
Application clock, package writes only
Package-managed timestamps use the application server's clock, not the database's, and only writes through the service set them. Raw SQL, migrations and other services do not. For timestamps that hold on every write path, let the database manage them.
How do I let the database manage createdAt and updatedAt?
Define the defaults in your Drizzle schema and turn the package's timestamps off.
Define the columns with database defaults
import { pgTable, serial, timestamp, varchar } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 100 }).notNull(),
email: varchar('email', { length: 255 }).notNull().unique(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true })
.defaultNow()
.notNull()
.$onUpdate(() => new Date()),
});defaultNow()lets the database setcreated_aton insert.$onUpdate(() => new Date())makes Drizzle setupdatedAton every update it builds, including the package's ownupdate().
Add a trigger for writes outside Drizzle
$onUpdate runs in Drizzle, so a script that runs UPDATE users SET name = ... directly skips it.
For an updated_at that holds even then, add a PostgreSQL trigger or a MySQL
ON UPDATE CURRENT_TIMESTAMP clause:
-- PostgreSQL
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER users_set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION set_updated_at();-- MySQL
ALTER TABLE users
MODIFY updated_at TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;Turn package timestamps off
DrizzleCrudModule.forRoot({
dialect: 'postgresql',
connectionString: process.env.DATABASE_URL,
schema,
defaults: { timestamps: false },
});The package then leaves the timestamp columns to the database. Leaving it on would overwrite the database default with the application clock on every create and update.
Package-managed or database-managed?
| Aspect | Package-managed | Database-managed |
|---|---|---|
| Clock | Application server | Database |
| Coverage | Writes through the service only | Every write, including raw SQL (with a trigger) |
| Clock control in tests | Fake timers on Date | Needs database time control |
| Setup | defaults: { timestamps: true } | defaultNow() and $onUpdate(), or triggers |
Package-managed timestamps fit when:
- Every write goes through the service, so coverage is not a concern.
- Tests need fixed times, since a faked
Datecontrols the values.
Database-managed timestamps fit when:
- Several writers touch the table: other services, scripts, manual SQL.
- Several app servers write, and you want one clock instead of each server's.
- You run in production and want the database to have the last word on time.
Can findAll sort by created_at by default?
Yes, as an opt-in. Set defaults.sortOrder: 'desc' in forRoot, and every entity without its own
defaultSort sorts findAll by its timestamps.createdAt key. An entity with timestamps off gets
no fallback. See pagination and sorting for the full sort rules.
Common questions
Yes, by default. create sets both, and update, softDelete and restore set updated_at, using the application clock.
Set timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } in the entity's forFeature config. The settings name keys in the Drizzle table object, not SQL column names.
Pass config: { timestamps: undefined } in forFeature. For the whole project, set defaults: { timestamps: false } in forRoot.
Only when it inserts. When the row already exists, the update keeps its created_at and sets updated_at to now.
Next steps
Soft delete in Drizzle ORM
deleted_at, the third timestamp column.
Hooks and validation
Set other fields in beforeCreate and beforeUpdate.
Pagination and sorting
defaultSort and the created_at fallback.
Soft delete in Drizzle ORM
Soft delete rows in NestJS with Drizzle ORM. A deleted_at column hides them from reads, restore brings them back and forceDelete purges.
Drizzle UUID primary keys in NestJS
Use a Drizzle uuid primary key in NestJS, or serial and bigint. The key type comes from the column; on MySQL you send the uuid on create.