Search code examples
datesanity

How to create a default `creationDate` for a document in sanity.io?


I have checked the documentation of how to do this, but I have not found an answer.

Basically, when a document is created/published, I want to set a createdDate for the document (as a read-only/hidden field).


Solution

  • As mentioned in svale's comment, it is possible to set both _createdAt and _updatedAt but only upon creation. I've been using Sanity's official JS client and it allows me to do this:

    await client.create({
        _type: "someType",
        _createdAt: "2019-12-31T12:34:56Z",
        _updatedAt: "2020-01-01T12:34:56Z",
    });
    

    Additionally, it's possible to set a custom _id if needed.

    When updating a document, those attributes are indeed read-only and cannot be manually changed.