Access to payload object on plugin initialization

default discord avatar
khakimvinhlast year
1 1

Hi everyone,
Is there a way to access the payload object inside plugin at the beginning?

The reason: I'm trying to build a plugin, which requires some initial data (kind of default value) to be write into the auth collection for the very first time the plug in got enabled.

I've checked the public-demo seed function, but it's called directly in the server.ts, not in the plugin config.

Any ideas appreciated, thanks.

  • Selected Answer
    discord user avatar
    denolfe
    last year

    Hey @khakimvinh , this is a great question. All config and plugin initialization is done before accessing the backend.

    If you need your plugin to perform some sort of action, your plugin could utilize the onInit function of the config, which gives it access to the payload local API. Here is an example:

      onInit: async (payload) => {
        await payload.create({
          collection: 'my-collection',
          data: {
            // Set field values here
          },
        });
      },

    Worth noting that if you populate this function inside of your plugin, any other onInit usage will likely be wiped out.

    Because this is a function and not a property that can be spread - what I'd recommend is having your plugin export an additional function that can be put into the main config's onInit. This would mitigate the above issue. Give that a go and let me know if you run into any issues 👍

    1 reply
  • default discord avatar
    khakimvinhlast year

    Thank you very much @denolfe
    I somehow missed the onInit in the doc...

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.