Hook into the Task Running Lifecycle
Nx plugins can hook into the task running lifecycle to execute custom logic before and after tasks are run. This is useful for implementing custom analytics, environment validation, or any other pre/post processing that should happen when running tasks.
These task execution hooks are the new API that replaces the deprecated Custom Tasks Runners. This feature is available since Nx 20.4+. For information about migrating from Custom Tasks Runners to these hooks, see Deprecating Custom Tasks Runner.
Task Execution Hooks
Nx provides two hooks that plugins can register:
preTasksExecution
: Runs before any tasks are executedpostTasksExecution
: Runs after all tasks are executed
These hooks allow you to extend Nx's functionality without affecting task execution or violating any invariants.
Creating Task Execution Hooks
To implement task execution hooks, create a plugin and export the preTasksExecution
and/or postTasksExecution
functions:
1// Example plugin with both pre and post execution hooks
2
3// context contains workspaceRoot and nx.json configuration
4export async function preTasksExecution(options: any, context) {
5 // Run custom logic before tasks are executed
6 console.log('About to run tasks!');
7
8 // You can modify environment variables
9 if (process.env.QA_ENV) {
10 process.env.NX_SKIP_NX_CACHE = 'true';
11 }
12
13 // You can validate the environment
14 if (!isEnvironmentValid()) {
15 throw new Error('Environment is not set up correctly');
16 }
17}
18
19// context contains workspaceRoot, nx.json configuration, and task results
20export async function postTasksExecution(options: any, context) {
21 // Run custom logic after tasks are executed
22 console.log('All tasks have completed!');
23
24 // You can access task results for analytics
25 if (options.reportAnalytics) {
26 await fetch(process.env.ANALYTICS_API, {
27 method: 'POST',
28 headers: {
29 'Content-Type': 'application/json',
30 },
31 body: JSON.stringify(context.taskResults),
32 });
33 }
34}
35
36function isEnvironmentValid() {
37 // Implement your validation logic
38 return true;
39}
40
Configuring Your Plugin
Configure your plugin in nx.json
by adding it to the plugins
array:
1{
2 "plugins": [
3 {
4 "plugin": "my-nx-plugin",
5 "options": {
6 "reportAnalytics": true
7 }
8 }
9 ]
10}
11
The options you specify in the configuration will be passed to your hook functions.
Maintaining State Across Command Invocations
By default, every plugin initiates a long-running process, allowing you to maintain state across command invocations. This is particularly useful for gathering advanced analytics or providing cumulative feedback.
Conditional Execution
You can implement conditional logic in your hooks to control when they run:
1export async function preTasksExecution(options, context) {
2 // Only run for specific environments
3 if (process.env.RUNNER !== 'production') return;
4
5 // Your pre-execution logic
6}
7
8export async function postTasksExecution(options, context) {
9 // Only run for specific task types
10 const hasAngularTasks = Object.keys(context.taskResults).some((taskId) =>
11 taskId.includes('angular')
12 );
13
14 if (!hasAngularTasks) return;
15
16 // Your post-execution logic
17}
18
Best Practices
- Keep hooks fast: Hooks should execute quickly to avoid slowing down the task execution process
- Handle errors gracefully: Ensure your hooks don't crash the entire execution pipeline
- Use environment variables for configuration that needs to persist across tasks
- Leverage context data: Use the context object to access relevant information about the workspace and task results
- Provide clear errors: If throwing errors, make sure they are descriptive and actionable