n8n is a visual automation platform that links triggers, processing nodes, and output nodes into workflows. It does not supply models itself; the models come from the API service you configure. For teams operating from mainland China, a common approach is to prepare an OpenAI-compatible gateway, configure a custom Base URL in n8n, and wire chat, summarization, and classification steps into business processes.
This article follows the order of an actual build: installation, preparing parameters, configuring credentials, running a workflow, handling errors, and finally team deployment. Interface labels change between versions, so treat your installed version as the source of truth.
Note: n8n is a trademark of n8n GmbH, and OpenAI is a trademark of OpenAI, Inc. This article is a technical integration guide only and implies no affiliation or partnership with those companies. Available models and prices are subject to the in-site model pricing page.
1. Cloud or self-hosted
n8n offers both cloud hosting and self-hosting. The cloud option removes server maintenance and suits quick validation. Self-hosting gives you control over data paths, network egress, and upgrade cadence, which suits teams with compliance requirements or the need for intranet access. This article focuses on self-hosting, because custom Base URLs, environment variables, and team permissions come up more often in that setting.
Self-hosting also carries costs: you are responsible for the server, database, backups, HTTPS, upgrades, and security configuration. Decide who will operate the instance before choosing self-hosting.
2. Installation and initialization
The officially recommended production method is Docker Compose; a single docker run command is enough for a local trial. The image is n8nio/n8n, the default port is 5678, and the data volume mounts at /home/node/.n8n. That directory holds not only the SQLite database but also encryption keys and other files, so it must be persisted.
docker volume create n8n_data
docker run -it --rm --name n8n \
-p 5678:5678 \
-e GENERIC_TIMEZONE="Asia/Shanghai" \
-e TZ="Asia/Shanghai" \
-e N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true \
-v n8n_data:/home/node/.n8n \
n8nio/n8n
After startup, open http://localhost:5678 and create the owner account when prompted. For production, do not run a single instance on SQLite long term: set DB_TYPE=postgresdb and the DB_POSTGRESDB_* connection variables to use PostgreSQL, and include the database in your backups. The npm route (npx n8n or a global install) is fine for local testing; the official documentation states that npm installation is deprecated as of n8n 3.0, and production should use Docker. Check the official installation documentation for Node.js requirements; the current range stated there is 20.19 through 24.x.
3. Prepare the key, Base URL, and model ID
Connecting to any OpenAI-compatible service requires just three parameters:
| Parameter | What to enter | Common mistake |
|---|---|---|
| API Key | Created in the gateway console, named by project | Copying it with a space or line break |
| Base URL | https://ai.zhongshangqihang.com/v1 |
Entering the full /chat/completions path |
| Model ID | The API identifier shown on the pricing page | Using a display name or an old version suffix |
Create the key after signing up for ZSQH AI Gateway. Use one key per environment, keeping test and production separate so a leaked key can be revoked on its own. Copy the model ID from the model pricing page, and pay attention to capitalization and version suffixes. Available models and billing methods change over time; the console and pricing page are authoritative.
4. Configure the OpenAI credential
In n8n, open Credentials in the left sidebar and create a new credential of type OpenAI. In the current version the fields include API Key, Organization ID (optional), and Base URL. When using a gateway, change the Base URL to the gateway address, usually ending at /v1 without /chat/completions. Organization ID is only needed when connecting to OpenAI directly with an account that belongs to multiple organizations; with a compatible gateway it is normally left blank.
A few practices:
- Keep the key in the credential only; never put it in a Code node, a Set node, or the workflow JSON.
- Name credentials by purpose, for example "gateway-prod-content-summary", not "test1".
- After saving, run the credential test. If it fails, check the Base URL and network egress first.
- On team instances, create credentials per project instead of sharing one key among many people.
- When self-hosting, safeguard
N8N_ENCRYPTION_KEY; after it changes, existing credentials may no longer decrypt.
5. Run the first workflow
Take "generate a reply draft after a form submission" as the example:
- Create a workflow and add a Form Trigger or Manual Trigger.
- Add an OpenAI node and set Resource to Text.
- Set Operation to Generate a Chat Completion; older versions call the equivalent operation Message a Model.
- Select the credential and model you just created, and pass form fields through expressions such as
{{ $json.message }}. - Constrain the role, output format, and length in the prompt to reduce irrelevant content.
- Add a Set node and keep only the fields later steps need.
- Add a Gmail, Slack, or spreadsheet node to write the result where it belongs.
- Execute manually first and inspect the input and output of each node before enabling the workflow.
If your gateway does not support the Responses API, do not choose Generate a Model Response; use the Chat Completions operation instead. Which parameters a node exposes depends on your n8n version and the gateway documentation.
6. Call compatible endpoints with the HTTP Request node
For parameters the node does not expose, batch requests, or special fields, use the HTTP Request node to call /v1/chat/completions directly. Set Method to POST, enter the full endpoint URL, and choose Predefined Credential Type with the OpenAI credential, or Bearer Auth under Generic Credential Type. Set Body to JSON and include the model, messages, and parameters.
Do not include the key in the request body; authentication is injected by the credential. Parse the response as an OpenAI Chat Completions structure, typically reading choices[0].message.content. If the response is streamed, either turn streaming off on the n8n side or handle server-sent events explicitly, otherwise parsing tends to fail.
7. Testing and error handling
Before debugging inside n8n, verify the address, key, and model with curl outside it; this saves a lot of time. For unattended workflows, treat failure as normal:
- Enable Retry On Fail in the node settings, retrying 2 to 3 times for 429, 5xx, and timeouts.
- Set a retry interval so you do not add pressure while rate-limited.
- Choose On Error by business need: stop, continue, or route the error output to an exception branch.
- Set a timeout on HTTP requests. Long text generation can be given more room, but it should never wait indefinitely.
- Configure an error workflow that sends the execution ID, node name, and an input summary to Slack or email.
- Check idempotency before retrying so you do not send duplicate messages or write duplicate rows.
| Symptom | Common cause | What to do |
|---|---|---|
| 401 | Wrong, expired, or unselected credential | Reselect the credential and check for stray spaces and key status |
| 403 | Model not enabled or insufficient permission | Verify model permissions and project limits |
| 404 | Wrong Base URL or endpoint path | Enter only up to /v1; do not include the full path |
| 429 | Too much concurrency or quota exceeded | Lower concurrency and enable backoff retries |
| 400 | Parameter not supported by the gateway | Remove incompatible fields and verify the model ID |
| Timeout | Slow network egress or upstream response | Check the proxy, DNS, and timeout settings |
8. Team deployment essentials
For team use, the point is not to create more accounts but to draw clear boundaries around credentials, projects, and operations:
- Use Projects to isolate business lines, assigning workflows and credentials to the right project.
- Issue keys per person and per project so a departure or leak can be handled with a targeted revocation.
- Serve production instances over HTTPS and set
N8N_WEBHOOK_URLto an externally reachable address; older versions used the variable nameWEBHOOK_URL. - In queue mode, all workers must use the same
N8N_ENCRYPTION_KEY, otherwise credentials cannot be decrypted. - Use an external task runner in production rather than running Code nodes in the main process.
- Back up both the database and the encryption key, storing them separately with access controls.
- Set a retention period for execution data to keep history from growing without bound and to reduce exposure of sensitive data.
Self-hosting is not automatic compliance. Whether the upstream model retains requests or uses them for training still needs separate confirmation; for processes involving customer privacy, add redaction and human review nodes.
FAQ
Does the n8n OpenAI node support a custom Base URL?
Yes. The current OpenAI credential includes a Base URL field, defaulting to https://api.openai.com/v1; change it to the gateway address. If your version lacks that field, the HTTP Request node with Bearer Auth can also make the call.
How far should the Base URL go?
Usually up to /v1, for example https://ai.zhongshangqihang.com/v1. Do not enter /v1/chat/completions, because the node appends the path itself. The most common symptom of the wrong level is a 404.
Why does the credential test pass but execution says the model does not exist?
A credential test usually verifies only the key and the address; it does not mean every model is available to you. Check that the model ID matches the pricing page, that the project has permission for that model, and that the request is not being routed to a different Base URL.
Must self-hosted n8n use PostgreSQL?
Not necessarily. SQLite works for testing and low traffic. Production usually moves to PostgreSQL for easier backups, concurrency, and scaling; follow the official Docker Compose documentation for specifics. Whichever database you use, persist the /home/node/.n8n directory.
What should a team watch when several people share an instance?
Split credentials by project and by person, and avoid long-lived shared keys. Use project roles to control access to workflows and credentials; enable HTTPS, MFA, and an external task runner in production; back up the encryption key and restrict access to it. If you need a unified model entry point and usage management, the gateway's virtual keys and quota features can help.
Next steps
The hard part of connecting n8n to a custom API is not dragging nodes; it is aligning three things: Base URL, key, and model ID. Get it working with curl first, then configure the OpenAI credential, and finally add retries, error branches, and team permissions. For a unified entry point, sign up for ZSQH AI Gateway; models and prices are subject to the model pricing page.
Related reading:
