Can you use a closure to track state between hooks?

The plugin forms a closure, and I was able to exploit that to pass state along locally. E.g.

let t;

module.exports = {
  name: 'test',
  init: () => t = 'test',
  finally: () => console.log(t)
};

returns

...

❯ Installing plugins dependencies

❯ Loading plugins
  Loading plugin "@netlify/plugin-functions-core" from build core
  Loading plugin from netlify-deployment-hours-plugin

❯ Running Netlify Build Lifecycle
  Found 3 steps. Lets do this!

┌─────────────────────────────────────┐
│ 1. Running init lifecycle from test │
└─────────────────────────────────────┘


 ✔  test.init completed in 7ms

┌──────────────────────────────────────────────────────────────────────────────────┐
│ 2. Running build lifecycle from build.lifecycle.build in netlify.yml config file │
└──────────────────────────────────────────────────────────────────────────────────┘

...

┌────────────────────────────────────────┐
│ 3. Running finally lifecycle from test │
└────────────────────────────────────────┘

t: test

 ✔  test.finally completed in 5ms

┌─────────────────────────────┐
│   Netlify Build Complete    │
└─────────────────────────────┘

 ✔  Netlify Build completed in 1778ms

(ノ◕ヮ◕)ノ*:・゚✧ Have a nice day!

Double-check: is that guaranteed every time? Some gotchas that could happen that I can think of:

  • Netlify uses a new container between hooks
  • Netlify re-uses a container across builds
  • Netlify imports the plugin multiple times between hooks for reasons

Hi @neverendingqs!
Thanks for reaching out!

Yes this is guaranteed. Each plugin runs in a separate process. That process starts before any hook is triggered and stops after all hooks have been triggered.

The top-level scope (let t;) will be called exactly once per build.

1 Like