TheGuardians
TheGuardians2mo ago

Bug

Hello, I have a problem. I'll explain. I connected Voiceflow to my N8N workflow and everything works fine, but when a user's question contains a line break, it breaks the JSON and crashes when sending the user message to my webhook. So, what can I do? Do I have to clean the message before sending it with a function, or do I simply have to modify my body in the API block?
No description
1 Reply
Tico | Voiceflow Assistant
When the API step builds the Raw Body it simply drops the value of your variable into the text you write. A JSON string cannot contain real line-break characters – they must be escaped as \n – so as soon as a user presses “Enter” the variable will inject an unescaped line-break and the JSON you ship to n8n becomes invalid. There are two safe ways to solve it: 1️⃣ Let the API step do the escaping for you
• Instead of using the Raw Body tab, switch to the Body key-value builder.
• Add a key (for example message) and set the value to {user_message}.
Because the builder serialises the object with JSON.stringify, any newline in the variable is automatically converted to \n, so the payload that reaches n8n is always valid. 2️⃣ Pre-clean the text in a Function step
If you must keep the Raw Body template, put a Function step right before the API call:
export default async function main({ inputVars }) {
const cleaned = inputVars.user_message.replace(/\n/g, "\\n");
return {
outputVars: { cleaned_message: cleaned },
};
}
export default async function main({ inputVars }) {
const cleaned = inputVars.user_message.replace(/\n/g, "\\n");
return {
outputVars: { cleaned_message: cleaned },
};
}
Then use "{cleaned_message}" in your Raw Body. The replace turns every real line break into the escaped sequence \n which keeps your JSON valid. Most builders choose option 1 because it’s simpler and you avoid having to maintain extra code, but either approach works. (Reference: API step → “Headers, Body and Parameters” – variables placed in the key-value Body area are stringified for you and therefore safely escaped.)

Did you find this page helpful?