Categories: n8nTechnical Tidbits

Code Smart in n8n: Programming Principles for Better Workflows

As a coder of 30+ years, I’ve learned that coding isn’t really about coding – it’s about logic, efficiency, and creativity under constraints. These fundamental principles are just as relevant in n8n as they are in traditional programming.

Sure, you can quickly learn n8n without any coding background. That’s one of its strengths! But understanding basic programming concepts can transform how you build workflows. Why? Because these time-tested principles help you create solutions that are:

  • Scalable: Your workflows can grow without becoming unwieldy
  • Maintainable: Easy to understand and modify months later
  • Efficient: Using fewer nodes and resources to accomplish more
  • Reusable: Building components you can copy across workflows
  • Reliable: Handling unexpected scenarios gracefully
  • Cost-effective: Minimizing server resources and processing time

I’m going to continually update this one post where I’ll share practical tips from my coding experience that can help make your n8n workflows more robust and professional. Each post will focus on a specific concept, showing how traditional programming wisdom applies in the n8n environment.

I’m not going to “deep dive” into any one element, rather just give my immediate thoughts on how I use n8n and that may give you a starting point for further research on your own.

The Switch Node:

TL;DR:

  • Always add a Fallback output – it’s your safety net
  • Switch nodes are better than IF nodes for complex logic
  • Use the visual flow to debug your logic rather than logs
  • Defensive programming prevents workflow failures

Common Gotchas:

  • Don’t skip the Fallback output just because you think you’ve covered all cases
  • Avoid chaining multiple IF nodes when a single Switch would work better
  • Don’t assume your data will always match your expected formats
  • Watch out for case sensitivity in your conditions.

Let’s start with one of the most common nodes used in n8n: the Switch node. It’s how you make decisions in your workflow – letting you send your data down different paths based on specific conditions.

My tip… always add a “fallback” output. You may think the only 2 possible outcomes is x, or y… but put in the Fallback output anyway. Without the Fallback, if for some unexpected reason the the calculation doesn’t end up being x or y, your workflow won’t just stop.

For example, imagine you’re processing customer orders and categorising them by size. You might think there are only two possibilities: ‘small’ or ‘large’. But what if someone enters ‘medium’ or leaves it blank? What if there’s an error on your site and it ends up showing “null” for the size? What if in the future you add a size and forget to update your n8n code to cater for that scenario? A fallback output helps you catch these unexpected cases and handle them gracefully.

The Fallback output can raise an error, or perform some other logic. This idea is the key tenet of “defensive programming”. It’s based on Murphy’s Law thinking: “anything that can go wrong, will go wrong.”

At the bottom of the Switch node select “Add option” and select “Fallback Output”:

Then once that’s selected, select the type of Fallback Output. In this case we want “Extra Output”.

And unlike when coding, with n8n you get a nice visual green line coming out the Fallback output so you can quickly see what’s going on.

I always use Switch nodes; never If nodes. If nodes are good for simply binary decisions – If this, then true, otherwise false (or even if this and that, then true, otherwise false):

While If nodes seem simpler at first with their AND/OR interface, they become unwieldy as your logic grows more complex. Switch nodes handle complex conditions more elegantly – think “if X then do A, else if Y then do B, otherwise do C” scenarios. If you start with an IF node, only to replace it later with a Switch node, you may break your workflow. Unlike traditional coding, n8n doesn’t make it easy to delete a node and replace it with something else, without breaking all the nodes that references it. Any nodes that reference the original If node will need updating, and n8n won’t automatically tell you which ones are affected – you’ll need to click into every node to check if anything’s broken. This is why it’s better to start with a Switch node if you think your logic might grow more complex over time.

This preference for SWITCH over multiple IF statements is sometimes called “structured programming” or “structured control flow.”

A tip specifically for use within n8n that can’t be used in traditional programming is to take advantage of the visual interface to better understand and debug complex Switch nodes. It goes against the principle of making code as efficient as possible, but for me personally I sometimes struggle to visualise complex Switch logic. So here’s what I do:

You might wonder why I’m using a Switch node when all paths lead to the same destination. I’m using it as a built-in debugging tool. While n8n doesn’t have easily accessible execution or error logs, nodes can serve as visual checkpoints. This Switch node lets me see exactly how my data flows – I can instantly spot that 56 items had no product_id, 3 lacked an SKU, and 75 items went through normally. It’s like having a transparent pipeline where I can see exactly where and how my data splits up. Better yet, I can click into the Switch node to inspect exactly which items went down each path.

This is one of the niceties of n8n, even for hard-code coders that may refuse to use no-code platforms (like, *cough* me, a couple of years ago). To be able to visualise logic branches like this and have a complete “log” of what went on inside that logic – all without writing it out into massively long text files, is pretty cool.

Oh, and… something else not easily done in traditional coding that you can do with n8n… name your outputs:


Relative versus Absolute references

TL;DR:

This tip is more about a quirk with n8n rather than anything else. Assume you have 2 Edit Fields nodes:

Quick sidebar on terminology: in traditional programming, we call these ‘variables’ – they’re basically containers that hold information. Just like you mighta box ‘Christmas decorations’ to store those items, a variable lets you give a name to some data so you can use it later. In n8n, they call this ‘Edit Fields’ or ‘Set Fields’ but it’s the same concept – you’re creating named containers for your data.

In the first node, I’ve set the variable “input” to “12345”:

In the 2nd Set Fields node I want to reference the “input” variable set in the first node:

I’ve just dragged the “input” from the left over to the “Fields to Set” on the right. n8n sets it as {{ $json.input }}.

This can be a problem and here’s why. What n8n is doing is referring to the “input” variable relatively, not absolutely.

In coding terms, relative references are like saying ‘get the value from the previous step’ while absolute references are like saying ‘get the value specifically from step X.’

When you drag a variable over in n8n, it creates a relative reference ({{ $json.input }}) which means ‘get the input value from whatever node comes right before this one.’ This seems convenient, but it’s fragile and here’s why…

Let’s say I want to put another Edit Fields node in between those two:

My new node in the middle is just setting another variable, “prompt_complete” to either true or false, depending on the value of the first node.

This will break the 3rd node (previously the 2nd node) because it’s still looking at ‘whatever comes right before’ which is now a different node.

Now, {{ $json.input }} is showing in red, meaning it can’t find anything called “input” in the previous node. The node is effectively broken.

In traditional coding, this issue doesn’t really come up because – and I’m simplifying things here – you always have to reference things absolutely anyway.

But the fun of n8n is that you can drag and drop things around willy-nilly so it’s really important to never use relative references.

An absolute reference ({{ $(‘Edit Fields’).item.json.input }}) is more robust because it specifically names which node to get the value from. It doesn’t matter what nodes you put in between – it will always look at that specific Edit Fields node.

And note a couple of screen shots back, the broken node didn’t have a red outline showing it was broken and that’s the killer. I wish the nodes would display they’re broken and in some nodes a broken reference will be highlighted by n8n, but reference issues in Set Fields nodes and Switch nodes do not raise any errors.


Comments in Code: Notes in n8n

I’ll let you in on a secret – the comments I write in my code aren’t for other people. They’re for me. Because let me tell you, Past Me and Present Me are often complete strangers to each other.

TL;DR:

The Great Comment Debate

In traditional coding, there’s this eternal debate about comments. Some developers argue they bloat the code. “Self-documenting code!” they cry. And sure, clean code is important, but here’s the thing – no code is self-documenting enough to explain why you chose that particular approach.

Why I Comment My Code (and My n8n Workflows)

Remember that brilliant idea you had at 2 AM? Yeah, neither will you in the morning. What seems crystal clear during a coding session can become a mystery after a good night’s sleep.

Here’s something interesting – I often solve problems just by writing comments about them. It’s like rubber duck debugging, but with yourself. Ever posted a question on Stack Overflow, only to figure out the answer while writing the question? Same principle. Comments force you to articulate your thinking.

Comments in the Age of AI

Comments are becoming even more valuable in the age of AI. When you’re asking ChatGPT or Claude to help with your code, they don’t just need to see what your code does – they need to understand why you’re doing it that way. Those contextual comments become crucial for AI to provide meaningful suggestions.

Notes in n8n: Better Than Code Comments

n8n actually gives us something better than traditional code comments – visual notes that can:

Pro Tip: Color Coding

I use different colored notes for different purposes:

The Personal Touch

Sometimes my comments read like a diary entry. “This is probably stupid but…” or “Future me, don’t touch this part!”, or even “Always returns 0. FML… Added code node to compensate. Ugh!!” And you know what? That’s perfectly fine. If you’re the only one who’ll read them, write them in whatever style works for you. I’ve written comments that were practically short stories, serving no other purpose that letting off steam. It all helps.

When to Write Notes

Building the Habit

Start small. Just add one note explaining why you built a workflow this way. Then maybe add another marking a tricky part you might forget. Before you know it, commenting becomes second nature. And trust me, Future You will be incredibly grateful.

Next time, I might talk about functions and how they can apply to n8n, and how we can use these same visual tools to structure our workflows in more maintainable ways.

demodomain

View Comments

Recent Posts

The Art and Science of Syncing with n8n: A Technical Deep-Dive

Syncing seems easy, right? Just grab data from System A, push it into System B,…

15 hours ago

Multi-Model, Multi-Platform AI Pipe in OpenWebUI

OpenWeb UI supports connections to OpenAI and any platform that supports the OpenAI API format…

1 week ago

The Open WebUI RAG Conundrum: Chunks vs. Full Documents

On Reddit, and elsewhere, a somewhat "hot" topic is using OWUI to manage a knowledge…

1 week ago

Case Study – provider agnostic AI chat interface

A client wanted a “chatbot” to interface with all of the providers (Google, OpenAI, Perplexity,…

2 weeks ago

Creating a “Custom GPT” with Open Web UI

Why pay $20 per month to OpenAI when you can do it for "free" using…

2 weeks ago

Upwork: A Freelancer’s Descent into Kafkaesque Absurdity

The gig economy. A promised land of flexibility, autonomy, and unlimited potential. Or so the…

2 weeks ago