
What is AI Agent on n8n? Optimize Your Workflow with n8n and AI Agent
In this era of digitalization and automation, optimizing workflows is one of the key factors that h…
Automating communication on messaging platforms has become an essential need for modern businesses. Among the available solutions, n8n stands out as a powerful tool that allows you to connect and automate workflows without requiring in-depth programming skills. This article will guide you on how to connect n8n with the Facebook Messenger API via Webhook, unlocking countless automation possibilities for your business.

n8n is an open-source workflow automation platform that provides a visual interface to connect various applications and services. Unlike many other solutions, n8n allows you to store data locally, ensuring maximum control and security.
Key benefits of using n8n compared to other tools on the market:
Before diving into the detailed guide, it's important to understand two fundamental concepts:
A webhook acts as a "digital listener," monitoring events and notifying your application when something happens. In the context of Facebook Messenger, the webhook will receive notifications when a new message is received and pass them to n8n for processing.
The Facebook Messenger API is a set of rules and protocols that allows your application to interact with the Messenger platform. Through this API, you can receive and send messages, access user information, and many other features.
Visit the Facebook Developer Portal.
Log in, then go to "My Apps" and click "Create App."
Fill in the basic information: app name, contact email, then click "Next."

In the Use Case section, select Other, then click Next.
In the Choose an App Type section, select Business, then click Next.
Then click Create App.
Open Terminal and type the following commands:
a. Install n8n:
bash
npm install n8n -g
b. Start n8n:
bash
n8n start
By default, the web interface will be available at http://localhost:5678.
Create a new workflow:
a. Click Create New Workflow from the dashboard.
b. Give it a recognizable name, e.g., [BNC] fbMessChatbot.
Find and add the "Webhook" node from the list
The configuration is as follows:
At this time, you copy the Test URL to test first. After running ok, use the Production URL.

Important: Facebook requires webhooks to use HTTPS. If you're running locally, you'll need to use a tunneling service like ngrok or Cloudflare Tunnel, or you can deploy n8n on a server to run and attach a domain to it, but this will cost you to rent a server.
Here, I will explain a little about how tunneling works. The tunneling service works by:
From the Dashboard, click "Settings" in the "Messenger" section
After going to the "Messenger API Setup" section, in the callback URL box, paste the webhook URL you just created earlier
In the code verification box, create any string

Then click the drop-down arrow (in the same row as "Configure webhook") and register the items that you want to give permission for the webhook to make. Here I still choose "massages".
Go back to n8n and click "Listen for test event".
Then, go back to Facebook Developer and click "Verify and Save."
At this point, you'll see the error "Unable to validate callback URL or verification code. Verify the information provided or try again later.", that's okay, because we need to go back to n8n and set up the "Responese webhook".

Despite the error, the webhook received the data. It's just that we need to set up a response so that Facebook recognizes that the data has been successfully transmitted.
Now, we need to add the "Edit Fields" node and drag the hub.chanllenge value (the left column) into the Fields to Set box and click "Test step" so that this node receives the previous data.

Then, add a "Response to webhook" node. In the "Respond with" section, select "Text", then drag the "hub.challenge" value in the left column to the "Respone Body" box, then click "Test step".

Now, you need to go back to the original webhook node, in the "Respond" section, select "Using 'Respond to Webhook node'".
Then you go out and click "Test workkflow" and then go to Facebook Developer in the "Configure webhook" earlier, click "Verify and save"
At this time, we need to connect to the page that we want to receive/send messages, so in the "Create access code" section, click connect then select and confirm the page as required.
Next, you click "Add Subscription" to register the items that this webhook is allowed to do. In case I want to set up a chatbot for Facebook Messenger, I will select at least the "messages" section.
After that, click "Generate" to generate the code. This code acts as your house key, anyone with a difficult key can enter. Be sure to copy this code.
Now if you want to test whether the webhook has received the message when someone sends a message to the fanpage, then you should go back to n8n, copy the "Production" link and then change the link again before changing the application to "Official".
Currently, our application is in the "Development" state, to switch to "Official", you go to the "Application Settings" section and select "Basic Information".
Fill in the "Privacy policy URL" box, then click Save changes and change the status from "Development" to "Official."
If you don't have this page available, visit this link to create a free copy.

You can access the "Explore Graph API" section in Faceook Developer, which can be accessed directly here.
Then select the app you just created under "Apps on Meta" (1).
Next, select the page that you want to connect to under "Users or pages" (2).
Then you give the permissions you want to give the app access and take the corresponding actions (3).
Finally click "Generate Access Token" (4).
Note, this is only a temporary token, which will expire for a period of time, so we need to set the validity period for this token.
You can go to the "Access code debugger" section or go directly here.
Paste the code you just came out earlier, then click "Debug" and then click the "Extended Access Code" button.
At this time, a new code will be returned, this code will never expire, so please feel free to use it. Copy this code to use for setting up the n8n side API.
First, if you have changed the webhook link to "Product URL", change it back to "Test URL" to make it easier to operate. (Still do the same as before, change the link -> Fill in the authentication code again -> click "Test workflow" (n8n side) -> click "Verify and save" (Facebook Developer side)).
Now, go back to the webhook node, in the "Settings" tab, check "AllowMultiple HTTP Methods" and then go back to the Parameters tab to check if there are 2 forms in the "HTTP Methods" section, "POST" and "GET".
For those who don't understand why there must be 2 Methods here:
Then continue to click "Test workflow" and then message the fanpage again to receive the data returned.

Then we continue to add the "Edit Fields" node in the POST branch, add 3 new fields and drag the "text" cells one by one and name them "text", "id" (just below the sender) and name them "sender_id", "id" (just below the recipent) and name them "page_id".
The purpose is to take out this content and use it for later, then click "Test step".

Similar to the GET webhook, in POST, Facebook also needs to receive a notification that the data has been sent successfully (within 1 minute), so before setting up the chatbot, we can add another node "Respond to webhook" to return the data to Facebook, avoiding the case that Facebook sends messages continuously because it does not receive a successful response.
We'll still install the same node as above. In the "Respond With" section, select "Text", and drag the text in the left column to the "Respond Body" box.

Then we branch out the new branch behind the "Edit Fields" node and add the note "AI Agent" to it. You can refer to AI Agent in this article.
n8n has a lot of built-in AI models that are trending today, most of which are free. The cost will depend on the developer but is generally not too expensive. In this article, I will demo with Google Gemini because this model has a free version.
First, we will reset the AI Agent first. For the current case (making a chatbot), we just change the "Prompt" to "Define below" and then drag "text" (the message sent by the customer) to the "Text" box, the AI will know by itself to answer this dialogue. If you have a more specific prompt, you can write more.

Then we set up the chat model for the Agent, here as I shared earlier, I will use Google Gemini because it is free.
For those of you who have not created a Google Gemini Credential, n8n always provides instructions for obtaining API keys, if you are lazy to read, you can refer to our instructions.
You go to this page, if you don't have an account, please create one.
Then click the "Create API key" button and select "Create with new project" (or if you already have a project on Google Cloud and want to use it).
Then copy this key and paste it and the API key box in the "Create New Credential" section.
Next in the "Model" box, you can choose which model suits your needs. Here, I only reply to messages with customers, I can choose Model 2.0 or 2.5.
Before setting up this section, we need to process the data in the AI return section first. Due to the return format that Facebook specifies is Json, there will be downline paragraphs in the AI answer, so before using this answer to send, we need to remove these downline (\n) characters.
Add the "Code" node. Select the code language as "JavaScript" and then paste this paragraph in:
let data = $input.first().json.output.replace(/(\r\n|\n|\r)/g, '');
return { 'data': data };
$input.first().json.output is the output variable (AI's answer), you can drag the variable from the left column in to avoid confusion, then bruise "Test step" to check again.

Add the "HTTP Request" node, select Method as POST.
In the URL box, fill in this link: https://graph.facebook.com/v22.0/{{page_id}}/messages
In which, page_id is the id of the recipient (the right-hand column - this is the recipient's id, i.e. your page id), you can drag in and replace this variable.
Optionally, turn on the "Send Headers" button, in the "Name" box fill in "Authorization", in the "Value" box fill in "Bearer {{page_token}}".
{{page_token}} is the Page token you generated earlier.

Then you go out, click "Test workflow" and message the page to see if the message has been received and sent successfully!
Now you enable the (active) workflow and change the URL of the webhook to "Production URL" and you are good to go.
After successfully establishing a basic connection, you can expand the chatbot's functionality:
Add Database nodes to store user information, interaction history, or other data. n8n supports a wide range of databases such as MongoDB, MySQL, PostgreSQL. This is the step to set up the memory (database) for the chatbot. You can also specify how many previous conversations the chatbot remembers, which is extremely convenient!
Connect with NLP services like DialogFlow or OpenAI to create smarter chat experiences, understand user intent, and respond accordingly.
In addition, to make the chatbot work smarter and smoother, you can set up additional MCPs to process information and some other tasks. For example, if you want the chatbot to advise on goods and close orders, send order confirmation emails, you should find relevant MCPs to set up the chatbot. MCP allows AI Agents to connect discrete tools into a real brain, helping AI Agents know what to do next without having to write too many complex prompts. I will post a simple MCP AI Agent setup guide in the next n8n, please follow along!
When implementing a Messenger chatbot with n8n, you may encounter some challenges:
Problem: Facebook limits the number of messages and how often they are sent.
Solution: Added queue handling logic and time spacing between message sends in n8n.
Problem: Webhooks can be hacked or abused.
Solution: Add authentication to the webhook and check Facebook's signature in each request.
Problem: An unstable network connection can cause message loss.
Solution: Add an Error Trigger node and an automatic retry mechanism in n8n.
Problem:
When you pause a workflow in n8n (deactivate) but keep the webhook in the Facebook Developer Portal active, Facebook continues to send events to the URL webhook. Since n8n workflow has been disabled, these events are not processed. Then, when you reactivate the workflow (activate), n8n will receive a series of cumulative requests from Facebook at the same time, causing a "trigger storm" - multiple executions that are triggered simultaneously.
Solution:
Instead of giving the n8n webhook URL directly to Facebook, you can set up an intermediate proxy:
Facebook → API Gateway/Proxy → n8n
This proxy can:
Disable n8n workflows, and disable Facebook webhook subscriptions
Create two different endpoint webhooks:

Connecting n8n to the Facebook Messenger API via webhooks opens up a wealth of possibilities for automating customer communication. While the setup process may be more complex than some other platforms like Telegram, the benefits of reaching billions of Facebook users are undeniable.
With this detailed guide, you already have a solid foundation for building a powerful Messenger chatbot using n8n - an open-source, flexible, and fully customizable solution for the specific needs of your business.
Get started today and witness how automated chatbots can significantly improve your customer experience and business performance!

In this era of digitalization and automation, optimizing workflows is one of the key factors that h…

Do you dream of a virtual assistant that can automate everything from data collection to customer in…

Zoho Forms and Google Forms are two leading tools for data collection, but which one is the right ch…