Context
The Context type provides type-safe access to resource state, lifecycle phase, and scope utilities within resource lifecycle handlers. It is automatically provided as thethis binding in Resource handlers.
Type Definition
phase property:
- CreateContext: Used when creating a new resource (
phase: "create") - UpdateContext: Used when updating an existing resource (
phase: "update") - DeleteContext: Used when deleting a resource (
phase: "delete")
Phase-Specific Contexts
CreateContext
Used during resource creation. Theoutput and props are undefined.
UpdateContext
Used during resource updates. Provides access to previous output and props.DeleteContext
Used during resource deletion. Provides access to the resource being deleted.Properties
'create' | 'update' | 'delete'
The current lifecycle phase of the resource.
Output | undefined
The previous output of the resource. Only available in
update and delete phases.Props | undefined
The previous props of the resource. Only available in
update and delete phases.string
The resource identifier provided when creating the resource.
string
The fully qualified name of the resource (e.g.,
"my-app/dev/my-resource").Scope
The scope containing this resource. Provides access to scope properties and methods.
string
The current stage name (e.g.,
"dev", "prod").boolean
Whether logging is suppressed.
boolean
Whether this resource is being created as a replacement for another resource.
Methods
destroy()
Terminates the resource lifecycle handler and marks the resource for deletion.boolean
default:"false"
Whether to retain child resources when destroying this resource.
DestroyedSignal)
Example:
replace()
Signals that the resource should be replaced (deleted then recreated). Used when an immutable property changes.boolean
default:"false"
Force replacement even if not necessary.
ReplacedSignal)
Example:
get()
Retrieves a value from the resource’s internal state storage.string
required
The key to retrieve.
undefined if not found.
Example:
set()
Stores a value in the resource’s internal state storage.string
required
The key to store.
T
required
The value to store.
delete()
Deletes a value from the resource’s internal state storage.string
required
The key to delete.
undefined if not found.
Example:
onCleanup()
Registers a cleanup function to run when the process exits.function
required
The cleanup function to register.
create()
Creates the resource output with Alchemy-managed properties.Omit<Output, keyof Resource>
required
The resource-specific properties (excludes internal Alchemy properties).
Examples
Phase-Based Logic
Using Context Methods
Handling Immutable Properties
Accessing Scope Properties
Type-Safe Phase Handling
Related
- Resource() - Define resource providers
- Scope - Scope API reference
- alchemy.secret() - Secret handling