Back to Catalog

Automated workflow & credential restoration system for self-hosted environments

FlorentFlorent
201 views
2/3/2026
Official Page

n8n Restore workflows & credentials from Disk - Self-Hosted Solution

This n8n template provides a safe and intelligent restore solution for self-hosted n8n instances, allowing you to restore workflows and credentials from disk backups.

Perfect for disaster recovery or migrating between environments, this workflow automatically identifies your most recent backup and provides a manual restore capability that intelligently excludes the current workflow to prevent conflicts. Works seamlessly with date-organized backup folders.

Good to know

  • This workflow uses n8n's native import commands (n8n import:workflow and n8n import:credentials)
  • Works with date-formatted backup folders (YYYY-MM-DD) for easy version identification
  • The restore process intelligently excludes the current workflow to prevent overwriting itself
  • Requires proper Docker volume configuration and file system permissions
  • All operations are performed server-side with no external dependencies
  • Compatible with backups created by n8n's export commands

How it works

Restore Process (Manual)

  1. Manual trigger with configurable pinned data options (credentials: true/false, workflows: true/false)
  2. The Init node sets up all necessary paths, timestamps, and configuration variables using your environment settings
  3. The workflow scans your backup folder and automatically identifies the most recent backup
  4. If restoring credentials:
    • Direct import from the latest backup folder using n8n's import command
    • Credentials are imported with their encrypted format intact
  5. If restoring workflows:
    • Scans the backup folder for all workflow JSON files
    • Creates a temporary folder with all workflows from the backup
    • Intelligently excludes the current restore workflow to prevent conflicts
    • Imports all other workflows using n8n's import command
    • Cleans up temporary files automatically
  6. Optional email notifications provide detailed restore summaries with command outputs

How to use

Prerequisites

  • Existing n8n backups in date-organized folder structure (format: /backup-folder/YYYY-MM-DD/)
  • Workflow backups as JSON files in the date folder
  • Credentials backups in subfolder: /backup-folder/YYYY-MM-DD/n8n-credentials/
  • For new environments: N8N_ENCRYPTION_KEY from source environment (see dedicated section below)

Initial Setup

  1. Configure your environment variables:

    • N8N_ADMIN_EMAIL: Your email for notifications (optional)
    • N8N_BACKUP_FOLDER: Location where your backups are stored (e.g., /files/n8n-backups)
    • N8N_PROJECTS_DIR: Projects root directory
    • GENERIC_TIMEZONE: Your local timezone
    • N8N_ENCRYPTION_KEY: Required if restoring credentials to a new environment (see dedicated section below)
  2. Update the Init node:

    • (Optional) Configure your email here: const N8N_ADMIN_EMAIL = $env.N8N_ADMIN_EMAIL || 'youremail@world.com';
    • Set PROJECT_FOLDER_NAME to "Workflow-backups" (or your preferred name)
    • Set credentials to "n8n-credentials" (or your backup credentials folder name)
    • Verify BACKUP_FOLDER path matches where your backups are stored
  3. Ensure your Docker setup has:

    • Mounted volume containing backups (e.g., /local-files:/files)
    • Access to n8n's CLI import commands
    • Proper file system permissions (read access to backup directories)

Performing a Restore

  1. Open the workflow and locate the "Start Restore" manual trigger node
  2. Edit the pinned data to choose what to restore:
    • credentials: true - Restore credentials
    • workflows: true - Restore workflows
    • Set both to true to restore everything
  3. Click "Execute workflow" on the "Start Restore" node to execute the restore
  4. The workflow will automatically find the most recent backup (latest date)
  5. Check the console logs or optional email for detailed restore summary

Important Notes

  • The workflow automatically excludes itself during restore to prevent conflicts
  • Credentials are restored with their encryption intact. If restoring to a new environment, you must configure the N8N_ENCRYPTION_KEY from the source environment (see dedicated section below)
  • Existing workflows/credentials with the same names will be overwritten
  • Test in a non-production environment first if unsure

⚠ Critical: N8N_ENCRYPTION_KEY Configuration

Why this is critical: n8n generates an encryption key automatically on first launch and saves it in the ~/.n8n/config file. However, if this file is lost (for example, due to missing Docker volume persistence), n8n will generate a NEW key, making all previously encrypted credentials inaccessible.

When you need to configure N8N_ENCRYPTION_KEY:

  • Restoring to a new n8n instance
  • When your data directory is not persisted between container recreations
  • Migrating from one server to another
  • As a best practice to ensure key persistence across updates

How credentials encryption works:

  • Credentials are encrypted with a specific key unique to each n8n instance
  • This key is auto-generated on first launch and stored in /home/node/.n8n/config
  • When you backup credentials, they remain encrypted but the key is NOT included
  • If the key file is lost or a new key is generated, restored credentials cannot be decrypted
  • Setting N8N_ENCRYPTION_KEY explicitly ensures the key remains consistent

Solution: Retrieve and configure the encryption key

Step 1: Get the key from your source environment

# Check if the key is defined in environment variables
docker-compose exec n8n printenv N8N_ENCRYPTION_KEY

If this command returns nothing, the key is auto-generated and stored in n8n's data volume:

# Enter the container
docker-compose exec n8n sh

# Check configuration file
cat /home/node/.n8n/config

# Exit container
exit

Step 2: Configure the key in your target environment

Option A: Using .env file (recommended for security)

# Add to your .env file
N8N_ENCRYPTION_KEY=your_retrieved_key_here

Then reference it in docker-compose.yml:

services:
  n8n:
    environment:
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}

Option B: Directly in docker-compose.yml (less secure)

services:
  n8n:
    environment:
      - N8N_ENCRYPTION_KEY=your_retrieved_key_here

Step 3: Restart n8n

docker-compose restart n8n

Step 4: Now restore your credentials

Only after configuring the encryption key, run the restore workflow with credentials: true.

Best practice for future backups:

  • Always save your N8N_ENCRYPTION_KEY in a secure location alongside your backups
  • Consider storing it in a password manager or secure vault
  • Document it in your disaster recovery procedures

Requirements

Existing Backups

  • Date-organized backup folders (YYYY-MM-DD format)
  • Backup files created by n8n's export commands or compatible format

Environment

  • Self-hosted n8n instance (Docker recommended)
  • Docker volumes mounted with access to backup location
  • Optional: SMTP server configured for email notifications

Credentials (Optional)

  • SMTP credentials for email notifications (if using email nodes)

Technical Notes

Smart Workflow Exclusion

  • During workflow restore, the current workflow's name is cleaned and matched against backup files
  • This prevents the restore workflow from overwriting itself
  • The exclusion logic handles special characters and spaces in workflow names
  • A temporary folder is created with all workflows except the current one

Timezone Handling

  • All timestamps use UTC for technical operations
  • Display times use local timezone for user-friendly readability
  • Backup folder scanning works with YYYY-MM-DD format regardless of timezone

Security

  • Credentials are imported in n8n's encrypted format (encryption preserved)
  • Ensure backup directories have appropriate read permissions
  • Consider access controls for who can trigger restore operations
  • No sensitive data is logged in console output

Troubleshooting

Common Issues

  1. No backups found: Verify the N8N_BACKUP_FOLDER path is correct and contains date-formatted folders
  2. Permission errors: Ensure Docker user has read access to backup directories
  3. Path not found: Verify all volume mounts in docker-compose.yml match your backup location
  4. Import fails: Check that backup files are in valid n8n export format
  5. Workflow conflicts: The workflow automatically excludes itself, but ensure backup files are properly named
  6. Credentials not restored: Verify the backup contains a n8n-credentials folder with credential files
  7. Credentials decrypt error: Ensure N8N_ENCRYPTION_KEY matches the source environment

Version Compatibility

  • Tested with n8n version 1.113.3
  • Compatible with Docker-based n8n installations
  • Requires n8n CLI access (available in official Docker images)

This workflow is designed for self-hosted server backup restoration. For FTP/SFTP remote backups, see the companion workflow "n8n Restore from FTP".

Works best with backups from: "Automated n8n Workflows & Credentials Backup to Local/Server Disk & FTP"

n8n Workflow: Basic Credential Restoration System (Placeholder)

This n8n workflow provides a foundational structure for what could become a credential restoration system. Based on its current definition, it does not implement any actual credential restoration logic. Instead, it demonstrates a workflow that can be manually triggered, includes conditional logic, the ability to execute shell commands, send emails, and handle errors.

Important Note: The current JSON definition for this workflow is a template or starter and does not contain the specific logic or configurations required for a functional credential restoration system. The node names and connections suggest a potential path, but the actual implementation details (like the commands to execute, email content, and conditional checks) are missing from the provided JSON.

What it does (as defined by the JSON):

  1. Manual Trigger: The workflow is designed to be executed manually, likely for testing or initiating a process on demand.
  2. Code Node: It includes a "Code" node, indicating that custom JavaScript logic can be inserted here. This is where the core logic for credential restoration (e.g., interacting with a database, API, or file system to retrieve/reset credentials) would typically reside.
  3. Conditional Logic (If): An "If" node allows for branching based on a condition. This could be used to check the success or failure of the credential restoration attempt.
  4. Execute Command: A "Execute Command" node is present, enabling the workflow to run shell commands on the host system. This is crucial for interacting with system-level tools or scripts for credential management.
  5. Send Email: An "Send Email" node is included, suggesting that notifications or restored credentials could be sent via email.
  6. Error Handling: A "Stop and Error" node is available to gracefully stop the workflow and signal an error condition, likely if the conditional logic determines a failure.
  7. Sticky Note: A "Sticky Note" node is present, serving as a placeholder for comments or documentation within the workflow itself.

Prerequisites/Requirements:

  • n8n Instance: A running n8n instance where this workflow can be imported.
  • SMTP Server Configuration: To send emails, your n8n instance needs to be configured with SMTP credentials.
  • Shell Access and Permissions: If the "Execute Command" node is to be used for sensitive operations, the n8n user on the host system must have the necessary permissions to run those commands.
  • Custom Code (JavaScript): The "Code" node will require custom JavaScript to be written and configured.

Setup/Usage:

  1. Import the Workflow:
    • In your n8n instance, navigate to "Workflows".
    • Click "New" or "Import from JSON".
    • Paste the provided JSON content into the import dialog.
  2. Configure Nodes:
    • Code Node: Edit the "Code" node (ID: 834) to add your specific JavaScript logic for credential restoration. This is the most critical step for making the workflow functional.
    • If Node: Configure the conditions in the "If" node (ID: 20) to evaluate the outcome of your custom code or command execution.
    • Execute Command Node: If using, configure the command to be executed in the "Execute Command" node (ID: 13).
    • Send Email Node: Configure the recipient, subject, and body of the email in the "Send Email" node (ID: 11). Ensure your SMTP credentials are set up in n8n.
    • Sticky Note: Update the "Sticky Note" (ID: 565) with relevant documentation for your specific implementation.
  3. Connect Nodes: The provided JSON shows no connections between the nodes. You will need to manually connect them in the n8n editor to define the flow logic. For example:
    • Connect "When clicking ‘Execute workflow’" to "Code".
    • Connect "Code" to "If".
    • Connect the "True" output of "If" to "Send Email" (for success).
    • Connect the "False" output of "If" to "Execute Command" (for a different action on failure) or "Stop and Error".
    • Connect "Execute Command" to "Send Email" (if the command's output needs to be emailed).
  4. Test the Workflow: Use the "Execute Workflow" button to test the flow and verify its functionality.

This README describes the potential of the provided n8n workflow template. To make it a fully functional credential restoration system, significant customization and configuration within the n8n editor are required.

Related Templates

Track competitor SEO keywords with Decodo + GPT-4.1-mini + Google Sheets

This workflow automates competitor keyword research using OpenAI LLM and Decodo for intelligent web scraping. Who this is for SEO specialists, content strategists, and growth marketers who want to automate keyword research and competitive intelligence. Marketing analysts managing multiple clients or websites who need consistent SEO tracking without manual data pulls. Agencies or automation engineers using Google Sheets as an SEO data dashboard for keyword monitoring and reporting. What problem this workflow solves Tracking competitor keywords manually is slow and inconsistent. Most SEO tools provide limited API access or lack contextual keyword analysis. This workflow solves that by: Automatically scraping any competitor’s webpage with Decodo. Using OpenAI GPT-4.1-mini to interpret keyword intent, density, and semantic focus. Storing structured keyword insights directly in Google Sheets for ongoing tracking and trend analysis. What this workflow does Trigger — Manually start the workflow or schedule it to run periodically. Input Setup — Define the website URL and target country (e.g., https://dev.to, france). Data Scraping (Decodo) — Fetch competitor web content and metadata. Keyword Analysis (OpenAI GPT-4.1-mini) Extract primary and secondary keywords. Identify focus topics and semantic entities. Generate a keyword density summary and SEO strength score. Recommend optimization and internal linking opportunities. Data Structuring — Clean and convert GPT output into JSON format. Data Storage (Google Sheets) — Append structured keyword data to a Google Sheet for long-term tracking. Setup Prerequisites If you are new to Decode, please signup on this link visit.decodo.com n8n account with workflow editor access Decodo API credentials OpenAI API key Google Sheets account connected via OAuth2 Make sure to install the Decodo Community node. Create a Google Sheet Add columns for: primarykeywords, seostrengthscore, keyworddensity_summary, etc. Share with your n8n Google account. Connect Credentials Add credentials for: Decodo API credentials - You need to register, login and obtain the Basic Authentication Token via Decodo Dashboard OpenAI API (for GPT-4o-mini) Google Sheets OAuth2 Configure Input Fields Edit the “Set Input Fields” node to set your target site and region. Run the Workflow Click Execute Workflow in n8n. View structured results in your connected Google Sheet. How to customize this workflow Track Multiple Competitors → Use a Google Sheet or CSV list of URLs; loop through them using the Split In Batches node. Add Language Detection → Add a Gemini or GPT node before keyword analysis to detect content language and adjust prompts. Enhance the SEO Report → Expand the GPT prompt to include backlink insights, metadata optimization, or readability checks. Integrate Visualization → Connect your Google Sheet to Looker Studio for SEO performance dashboards. Schedule Auto-Runs → Use the Cron Node to run weekly or monthly for competitor keyword refreshes. Summary This workflow automates competitor keyword research using: Decodo for intelligent web scraping OpenAI GPT-4.1-mini for keyword and SEO analysis Google Sheets for live tracking and reporting It’s a complete AI-powered SEO intelligence pipeline ideal for teams that want actionable insights on keyword gaps, optimization opportunities, and content focus trends, without relying on expensive SEO SaaS tools.

Ranjan DailataBy Ranjan Dailata
161

Generate song lyrics and music from text prompts using OpenAI and Fal.ai Minimax

Spark your creativity instantly in any chat—turn a simple prompt like "heartbreak ballad" into original, full-length lyrics and a professional AI-generated music track, all without leaving your conversation. 📋 What This Template Does This chat-triggered workflow harnesses AI to generate detailed, genre-matched song lyrics (at least 600 characters) from user messages, then queues them for music synthesis via Fal.ai's minimax-music model. It polls asynchronously until the track is ready, delivering lyrics and audio URL back in chat. Crafts original, structured lyrics with verses, choruses, and bridges using OpenAI Submits to Fal.ai for melody, instrumentation, and vocals aligned to the style Handles long-running generations with smart looping and status checks Returns complete song package (lyrics + audio link) for seamless sharing 🔧 Prerequisites n8n account (self-hosted or cloud with chat integration enabled) OpenAI account with API access for GPT models Fal.ai account for AI music generation 🔑 Required Credentials OpenAI API Setup Go to platform.openai.com → API keys (sidebar) Click "Create new secret key" → Name it (e.g., "n8n Songwriter") Copy the key and add to n8n as "OpenAI API" credential type Test by sending a simple chat completion request Fal.ai HTTP Header Auth Setup Sign up at fal.ai → Dashboard → API Keys Generate a new API key → Copy it In n8n, create "HTTP Header Auth" credential: Name="Fal.ai", Header Name="Authorization", Header Value="Key [Your API Key]" Test with a simple GET to their queue endpoint (e.g., /status) ⚙️ Configuration Steps Import the workflow JSON into your n8n instance Assign OpenAI API credentials to the "OpenAI Chat Model" node Assign Fal.ai HTTP Header Auth to the "Generate Music Track", "Check Generation Status", and "Fetch Final Result" nodes Activate the workflow—chat trigger will appear in your n8n chat interface Test by messaging: "Create an upbeat pop song about road trips" 🎯 Use Cases Content Creators: YouTubers generating custom jingles for videos on the fly, streamlining production from idea to audio export Educators: Music teachers using chat prompts to create era-specific folk tunes for classroom discussions, fostering interactive learning Gift Personalization: Friends crafting anniversary R&B tracks from shared memories via quick chats, delivering emotional audio surprises Artist Brainstorming: Songwriters prototyping hip-hop beats in real-time during sessions, accelerating collaboration and iteration ⚠️ Troubleshooting Invalid JSON from AI Agent: Ensure the system prompt stresses valid JSON; test the agent standalone with a sample query Music Generation Fails (401/403): Verify Fal.ai API key has minimax-music access; check usage quotas in dashboard Status Polling Loops Indefinitely: Bump wait time to 45-60s for complex tracks; inspect fal.ai queue logs for bottlenecks Lyrics Under 600 Characters: Tweak agent prompt to enforce fuller structures like [V1][C][V2][B][C]; verify output length in executions

Daniel NkenchoBy Daniel Nkencho
601

Automate invoice processing with OCR, GPT-4 & Salesforce opportunity creation

PDF Invoice Extractor (AI) End-to-end pipeline: Watch Drive ➜ Download PDF ➜ OCR text ➜ AI normalize to JSON ➜ Upsert Buyer (Account) ➜ Create Opportunity ➜ Map Products ➜ Create OLI via Composite API ➜ Archive to OneDrive. --- Node by node (what it does & key setup) 1) Google Drive Trigger Purpose: Fire when a new file appears in a specific Google Drive folder. Key settings: Event: fileCreated Folder ID: google drive folder id Polling: everyMinute Creds: googleDriveOAuth2Api Output: Metadata { id, name, ... } for the new file. --- 2) Download File From Google Purpose: Get the file binary for processing and archiving. Key settings: Operation: download File ID: ={{ $json.id }} Creds: googleDriveOAuth2Api Output: Binary (default key: data) and original metadata. --- 3) Extract from File Purpose: Extract text from PDF (OCR as needed) for AI parsing. Key settings: Operation: pdf OCR: enable for scanned PDFs (in options) Output: JSON with OCR text at {{ $json.text }}. --- 4) Message a model (AI JSON Extractor) Purpose: Convert OCR text into strict normalized JSON array (invoice schema). Key settings: Node: @n8n/n8n-nodes-langchain.openAi Model: gpt-4.1 (or gpt-4.1-mini) Message role: system (the strict prompt; references {{ $json.text }}) jsonOutput: true Creds: openAiApi Output (per item): $.message.content → the parsed JSON (ensure it’s an array). --- 5) Create or update an account (Salesforce) Purpose: Upsert Buyer as Account using an external ID. Key settings: Resource: account Operation: upsert External Id Field: taxid_c External Id Value: ={{ $json.message.content.buyer.tax_id }} Name: ={{ $json.message.content.buyer.name }} Creds: salesforceOAuth2Api Output: Account record (captures Id) for downstream Opportunity. --- 6) Create an opportunity (Salesforce) Purpose: Create Opportunity linked to the Buyer (Account). Key settings: Resource: opportunity Name: ={{ $('Message a model').item.json.message.content.invoice.code }} Close Date: ={{ $('Message a model').item.json.message.content.invoice.issue_date }} Stage: Closed Won Amount: ={{ $('Message a model').item.json.message.content.summary.grand_total }} AccountId: ={{ $json.id }} (from Upsert Account output) Creds: salesforceOAuth2Api Output: Opportunity Id for OLI creation. --- 7) Build SOQL (Code / JS) Purpose: Collect unique product codes from AI JSON and build a SOQL query for PricebookEntry by Pricebook2Id. Key settings: pricebook2Id (hardcoded in script): e.g., 01sxxxxxxxxxxxxxxx Source lines: $('Message a model').first().json.message.content.products Output: { soql, codes } --- 8) Query PricebookEntries (Salesforce) Purpose: Fetch PricebookEntry.Id for each Product2.ProductCode. Key settings: Resource: search Query: ={{ $json.soql }} Creds: salesforceOAuth2Api Output: Items with Id, Product2.ProductCode (used for mapping). --- 9) Code in JavaScript (Build OLI payloads) Purpose: Join lines with PBE results and Opportunity Id ➜ build OpportunityLineItem payloads. Inputs: OpportunityId: ={{ $('Create an opportunity').first().json.id }} Lines: ={{ $('Message a model').first().json.message.content.products }} PBE rows: from previous node items Output: { body: { allOrNone:false, records:[{ OpportunityLineItem... }] } } Notes: Converts discount_total ➜ per-unit if needed (currently commented for standard pricing). Throws on missing PBE mapping or empty lines. --- 10) Create Opportunity Line Items (HTTP Request) Purpose: Bulk create OLIs via Salesforce Composite API. Key settings: Method: POST URL: https://<your-instance>.my.salesforce.com/services/data/v65.0/composite/sobjects Auth: salesforceOAuth2Api (predefined credential) Body (JSON): ={{ $json.body }} Output: Composite API results (per-record statuses). --- 11) Update File to One Drive Purpose: Archive the original PDF in OneDrive. Key settings: Operation: upload File Name: ={{ $json.name }} Parent Folder ID: onedrive folder id Binary Data: true (from the Download node) Creds: microsoftOneDriveOAuth2Api Output: Uploaded file metadata. --- Data flow (wiring) Google Drive Trigger → Download File From Google Download File From Google → Extract from File → Update File to One Drive Extract from File → Message a model Message a model → Create or update an account Create or update an account → Create an opportunity Create an opportunity → Build SOQL Build SOQL → Query PricebookEntries Query PricebookEntries → Code in JavaScript Code in JavaScript → Create Opportunity Line Items --- Quick setup checklist 🔐 Credentials: Connect Google Drive, OneDrive, Salesforce, OpenAI. 📂 IDs: Drive Folder ID (watch) OneDrive Parent Folder ID (archive) Salesforce Pricebook2Id (in the JS SOQL builder) 🧠 AI Prompt: Use the strict system prompt; jsonOutput = true. 🧾 Field mappings: Buyer tax id/name → Account upsert fields Invoice code/date/amount → Opportunity fields Product name must equal your Product2.ProductCode in SF. ✅ Test: Drop a sample PDF → verify: AI returns array JSON only Account/Opportunity created OLI records created PDF archived to OneDrive --- Notes & best practices If PDFs are scans, enable OCR in Extract from File. If AI returns non-JSON, keep “Return only a JSON array” as the last line of the prompt and keep jsonOutput enabled. Consider adding validation on parsing.warnings to gate Salesforce writes. For discounts/taxes in OLI: Standard OLI fields don’t support per-line discount amounts directly; model them in UnitPrice or custom fields. Replace the Composite API URL with your org’s domain or use the Salesforce node’s Bulk Upsert for simplicity.

Le NguyenBy Le Nguyen
942