Cr4shBarcode
Cr4shBarcode2mo ago

How to Use the Javascript Step to Establish a Variable?

The API I'm working with requires the current date as a variable. Since I don't want the user to have to enter this information, I created a Javascript step that establishes the date in the correct format that I need. The problem is, how to I pass this variable to the API? In the documentation it states that the Javascript step can't be used to create new variables. Is there a way to introduce the variable earlier? Any YouTube tutorials I've found use a function to get the date (I'm avoiding this because I don't know how to write functions). Is there any solution to this, or am I going to have to find a way to change my Javascript code into a function step?
No description
2 Replies
Tico | Voiceflow Assistant
How to pass a date you build in a JavaScript Step to an API Step
1. Create the variable first
• Open the Variables panel (left side-bar) and add a new variable, e.g. current_date.
• You can leave its default value blank – it just needs to exist before the JS step runs.
2. Set the value in a JavaScript Step
Drag a JavaScript step right after Start and add something like:
// `current_date` already exists in the project
const now = new Date();
// format YYYY-MM-DD (change if your API needs something else)
current_date = now.toISOString().slice(0, 10);

// `current_date` already exists in the project
const now = new Date();
// format YYYY-MM-DD (change if your API needs something else)
current_date = now.toISOString().slice(0, 10);

The JS step can re-assign any existing variable; it just can’t create new ones – that’s the limitation mentioned in the docs. 3. Use the variable in your API Step
• In the API block, reference it exactly as {current_date} anywhere you need it – URL path, query-param, header or body.
• Example raw JSON body:
{
"date": "{current_date}"
}

{
"date": "{current_date}"
}

That’s it: the flow is Start → JS step (sets formatted date) → API step (sends it).
You do not need to convert the code into a Function unless you want to reuse it across projects; the simple JS step works fine for one-off logic. Docs for reference: https://docs.voiceflow.com/en/references/javascript-step
W. Williams (SFT)
VF vars are already defined. You don't need to use "const", "var", or "let" with them. Local variables need to be instantiated.

Did you find this page helpful?