ๆƒฏๆ€ง่šๅˆ ้ซ˜ๆ•ˆ่ฟฝ่ธชๅ’Œ้˜…่ฏปไฝ ๆ„Ÿๅ…ด่ถฃ็š„ๅšๅฎขใ€ๆ–ฐ้—ปใ€็ง‘ๆŠ€่ต„่ฎฏ
้˜…่ฏปๅŽŸๆ–‡ ๅœจๆƒฏๆ€ง่šๅˆไธญๆ‰“ๅผ€

ๆŽจ่่ฎข้˜…ๆบ

P
Privacy International News Feed
WordPressๅคงๅญฆ
WordPressๅคงๅญฆ
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
K
Kaspersky official blog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
G
GRAHAM CLULEY
N
News | PayPal Newsroom
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog
็พŽ
็พŽๅ›ขๆŠ€ๆœฏๅ›ข้˜Ÿ
J
Java Code Geeks
I
Intezer
The Cloudflare Blog
SecWiki News
SecWiki News
S
Secure Thoughts
Microsoft Azure Blog
Microsoft Azure Blog
V2EX - ๆŠ€ๆœฏ
V2EX - ๆŠ€ๆœฏ
C
Cyber Attacks, Cyber Crime and Cyber Security
ๅฅ‡ๅฎขSolidotโ€“ไผ ้€’ๆœ€ๆ–ฐ็ง‘ๆŠ€ๆƒ…ๆŠฅ
ๅฅ‡ๅฎขSolidotโ€“ไผ ้€’ๆœ€ๆ–ฐ็ง‘ๆŠ€ๆƒ…ๆŠฅ
Spread Privacy
Spread Privacy
D
DataBreaches.Net
S
Security Affairs
Help Net Security
Help Net Security
S
Securelist
F
Full Disclosure
C
Check Point Blog
F
Fortinet All Blogs
Know Your Adversary
Know Your Adversary
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Y
Y Combinator Blog
ไบ‘้ฃŽ็š„ BLOG
ไบ‘้ฃŽ็š„ BLOG
้˜ฎไธ€ๅณฐ็š„็ฝ‘็ปœๆ—ฅๅฟ—
้˜ฎไธ€ๅณฐ็š„็ฝ‘็ปœๆ—ฅๅฟ—
The Register - Security
The Register - Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
ไบบไบบ้ƒฝๆ˜ฏไบงๅ“็ป็†
ไบบไบบ้ƒฝๆ˜ฏไบงๅ“็ป็†
ๅš
ๅšๅฎขๅ›ญ_้ฆ–้กต
G
Google Developers Blog
Google Online Security Blog
Google Online Security Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
้…ท ๅฃณ โ€“ CoolShell
้…ท ๅฃณ โ€“ CoolShell
I
InfoQ
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Hacker News: Front Page
L
LINUX DO - ็ƒญ้—จ่ฏ้ข˜
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Donโ€™t Fail โ€” They Drift Spilling beans for how i learn for exam๐Ÿ˜"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" โ€” What Actually Happened Comfy Cloudโ€™s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions โ€” here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components โ€” Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cรณmo construรญ un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 ๐Ÿš€ I Built an Ethical Hacking Scanner Tool โ€“ Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points โ€” Here's What I Found About How Markets Really Move EcoTrack AI โ€” Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead โ€” I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve โ€” no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like Youโ€™re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace โ€” how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025โ€“62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D โ€” A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent โ€” It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly โ€” 2026/04/10โ€“04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI ้€ฑๅ ฑ โ€” 2026/04/10โ€“2026/04/17 ๆจกๅž‹ๅฐ้Ž–ๆฝฎไพ†ไบ†๏ผŒไฝ†ๅทฅๅ…ท้ˆๆ‰ๆ˜ฏ็œŸๆˆฐๅ ด Maybe this is how Open-Source apps are born... ๐Ÿš€ Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge โ€” $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase โ€” Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train โ€” Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extraรงรฃo de Vรญdeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life โ€” Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 โ€” Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows โ€” Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTrackingๅฎ‰่ฃ…ๅ’ŒiPhone้ขๆ•้…็ฝฎๆ•™็จ‹๏ผŒๆœ‰bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Threw Away My ILIKE Queries and My Search Bar Finally Works - MeiliSearch
Subham ยท 2026-05-02 ยท via DEV Community

MeiliSearch - The Complete Production Setup Guide (2026)

How I Ended Up Down the Search Engine Rabbit Hole

Okay so here's the thing. I was building a personal finance tracker for myself. Nothing fancy, just something to manage my accounts, transactions, EMI schedules, investment positions... you know, the usual "I got tired of 10 Google Sheets" kind of project. The backend was NestJS + Postgres/Prisma, clean architecture, the works.

At some point I added a global search bar to the frontend. Cmd+K style. You type, results appear across accounts, investments, transactions, all at once. Simple enough to want. Absolutely not simple to build correctly.

My first thought was "just ILIKE %query% in Postgres." Worked for 2 minutes. Then I tried to search for something with a typo and got zero results. Tried to search across 3 tables at once and ended up with the most cursed SQL JOIN you've ever seen. Tried to highlight matching text and gave up.

That's when I actually sat down and looked at what people use for this properly.


Picking a Search Engine: The Honest Comparison

Here's the deal โ€” there are more options than you'd expect, and most tutorials just pick one without explaining why. Let me actually show you the landscape:

Engine Open Source Typo Tolerance Hosting Setup Complexity Speed Best For
Elasticsearch Yes (BSL) Configurable Self-host / Elastic Cloud High โ€” JVM, configs, mappings Fast at scale Log analytics, massive datasets, enterprise
OpenSearch Yes (Apache 2) Configurable Self-host / AWS High โ€” same as ES Fast at scale AWS shops, ES alternative
Algolia No (SaaS) Built-in Managed only Very low Very fast Startups with budget, e-commerce
Typesense Yes (GPL) Built-in Self-host / Cloud Medium Very fast Algolia alternative, smaller datasets
MeiliSearch Yes (MIT) Built-in Self-host Low Very fast Developer experience, side projects to production
Postgres FTS Yes No Same DB Zero Okay Simple apps, already on Postgres
SQLite FTS5 Yes No Same DB Zero Fast for small CLI tools, local apps

Here's my honest take after going through this:

Elasticsearch is incredibly powerful but it genuinely feels like you need a DevOps certification to operate it in production. It's a JVM app. The config surface area is enormous. For log analytics at scale? Perfect. For a product search bar on a side project? Way overkill.

Algolia is the opposite โ€” it just works, the DX is amazing, and you'll have search running in 20 minutes. Then you look at the pricing for anything above 10k operations/month and close the tab.

Typesense is solid and worth looking at. The API is clean, performance is great. Honestly, if you're choosing between Typesense and MeiliSearch today, it's genuinely close.

MeiliSearch is what I went with. MIT licensed, Docker image is tiny (~50MB), search results appear in <50ms in most cases, typo tolerance works out of the box, and the JS SDK is properly typed. The configuration model is simple enough that I understood the whole thing in one afternoon. It also has the best NestJS integration story of the bunch.

If you're on Postgres already and your search needs are genuinely simple (one table, no typo tolerance needed), pg_trgm or full text search is worth trying first. But the moment you want multi-index search, typo tolerance, or highlighted snippets โ€” reach for a dedicated engine.

I'm using MeiliSearch. The rest of this post is the complete production setup.


Before You Touch Any Code โ€” Read These Five Rules

I spent about half a day debugging issues that all traced back to violating one of these. Saving you the pain:

Rule 1 โ€” MEILISEARCH_URL is the only thing that changes between environments.
Your NestJS code never hardcodes a host. It always reads from process.env.MEILISEARCH_URL. The .env file is what changes per machine, per deployment topology. Code stays identical everywhere.

Rule 2 โ€” Never use the Master Key in your application code.
The master key is a one-time bootstrap tool. Use it once to generate scoped API keys, then your app only ever uses those scoped keys. The master key never appears in search.service.ts or any NestJS code.

Rule 3 โ€” Always pin the MeiliSearch Docker image version.
Never use :latest. It silently upgrades between incompatible versions and corrupts your database on restart. Always pin: getmeili/meilisearch:v1.37.0.

Rule 4 โ€” MEILI_ENV=production is not optional.
Development mode accepts unauthenticated requests โ€” a security hole. Production mode enforces API key auth on every request. Always set this regardless of environment.

Rule 5 โ€” Port 7700 must always be reachable from wherever NestJS runs.
MeiliSearch always runs in Docker. NestJS might run in Docker, raw on the same machine, or on a completely different server. The only requirement: port 7700 on the MeiliSearch host must be reachable from wherever NestJS is.


How MEILISEARCH_URL Works Across All Deployments

This is the entire mental model. Everything else follows from it.

Deployment scenario Where NestJS runs Where MeiliSearch runs MEILISEARCH_URL in .env
Local dev โ€” both in Docker Compose Docker container Docker container (same compose) http://meilisearch:7700
Local dev โ€” NestJS raw, Meili in Docker Directly on Windows/Mac/Linux host Docker on same machine http://localhost:7700
Production โ€” both in Docker Compose Docker container Docker container (same compose) http://meilisearch:7700
Production โ€” NestJS on server, Meili on same server Directly on Linux server Same server (Docker, port exposed) http://localhost:7700
Production โ€” NestJS on one server, Meili on separate server Server A Server B http://<SERVER_B_IP>:7700

The rule in one sentence: If NestJS and MeiliSearch are in the same Docker Compose network, use the service name meilisearch. If NestJS is outside Docker (running raw on a host), use localhost or the remote server IP depending on where MeiliSearch is.

Most of us doing local dev run NestJS raw (npm run start:dev) and MeiliSearch in Docker. That's Scenario A:

Your Machine
โ”œโ”€โ”€ NestJS โ†’ runs raw (npm run start:dev)
โ””โ”€โ”€ Docker Desktop
    โ””โ”€โ”€ meilisearch container โ†’ port 7700 exposed to host

Enter fullscreen mode Exit fullscreen mode

Your .env just needs:

MEILISEARCH_URL=http://localhost:7700

Enter fullscreen mode Exit fullscreen mode

When Docker exposes ports: "7700:7700", port 7700 inside the container maps to port 7700 on your machine. Your NestJS talks to localhost:7700 like any other local service. Works on Windows, Mac, Linux as long as Docker Desktop is running.


Directory Structure

Here's what the full setup looks like before we start writing files:

project-root/
โ”œโ”€โ”€ .env                              โ† secrets for this machine โ€” never commit
โ”œโ”€โ”€ .env.example                      โ† committed template with placeholder values
โ”œโ”€โ”€ docker-compose.yml                โ† runs MeiliSearch (and optionally your app)
โ”œโ”€โ”€ Dockerfile                        โ† only needed if you run NestJS in Docker too
โ”œโ”€โ”€ scripts/
โ”‚   โ””โ”€โ”€ create-meili-keys.sh          โ† one-time key generation (run once per environment)
โ””โ”€โ”€ src/
    โ””โ”€โ”€ search/
        โ”œโ”€โ”€ index.ts                  โ† barrel
        โ”œโ”€โ”€ search.module.ts          โ† @Global module
        โ”œโ”€โ”€ search.service.ts         โ† MeiliSearch client wrapper
        โ”œโ”€โ”€ search.config.ts          โ† config via ConfigService
        โ””โ”€โ”€ indexes/
            โ”œโ”€โ”€ index.ts              โ† barrel
            โ””โ”€โ”€ [feature].index.ts   โ† one file per index (settings + type-safe queries)

Enter fullscreen mode Exit fullscreen mode


โš ๏ธ Important SDK Fixes โ€” Read Before Writing Any Code (v0.40+)

Three breaking changes caught me off guard. Flagging them upfront:

1. Client casing changed. The meilisearch npm package updated its primary export from MeiliSearch to Meilisearch (lowercase s). If you hit TypeError: MeiliSearch is not a constructor, this is why. Use the lowercase variant everywhere:

// โŒ Old
import { MeiliSearch } from 'meilisearch';
const client = new MeiliSearch({ ... });

// โœ… Current
import { Meilisearch } from 'meilisearch';
const client = new Meilisearch({ ... });

Enter fullscreen mode Exit fullscreen mode

2. waitForTask moved. client.waitForTask() no longer exists on the root client. Use client.tasks.waitForTask(uid). Also, tasks that fail (like "index already exists") no longer throw โ€” they return a task object where status === 'failed'. Always check completedTask.status === 'failed' explicitly.

3. Rate limiting on search endpoints. A global search bar triggering parallel requests (hitting /search for 4 indices at once) will instantly exhaust default NestJS Throttler limits (10 req/min), giving HTTP 429. Fix: add @Throttle({ default: { limit: 120, ttl: 60000 } }) on your search controllers.


Step 1 โ€” .env File

Create .env in your project root. Never commit this file.

# โ”€โ”€โ”€ MeiliSearch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
#
# Set MEILISEARCH_URL to match YOUR deployment topology:
#
#   NestJS in Docker + MeiliSearch in same Docker Compose:
#     MEILISEARCH_URL=http://meilisearch:7700
#
#   NestJS running raw on same machine as MeiliSearch Docker:
#     MEILISEARCH_URL=http://localhost:7700
#
#   NestJS on a separate server from MeiliSearch:
#     MEILISEARCH_URL=http://<MEILISEARCH_SERVER_IP>:7700
#
MEILISEARCH_URL=http://localhost:7700

MEILISEARCH_MASTER_KEY=your-master-key-minimum-16-chars-change-this
MEILISEARCH_BACKEND_KEY=fill-this-in-after-step-4
MEILISEARCH_SEARCH_KEY=fill-this-in-after-step-4

Enter fullscreen mode Exit fullscreen mode

Commit .env.example (safe to commit, no real values):

MEILISEARCH_URL=REPLACE_ME_see_comments_above
MEILISEARCH_MASTER_KEY=REPLACE_ME_min_16_chars
MEILISEARCH_BACKEND_KEY=REPLACE_ME_after_key_generation
MEILISEARCH_SEARCH_KEY=REPLACE_ME_after_key_generation

Enter fullscreen mode Exit fullscreen mode

Generate a strong master key: openssl rand -hex 32
Minimum 16 characters required in production mode. 32+ recommended.


Step 2 โ€” docker-compose.yml

This file runs MeiliSearch. It does not include your NestJS app โ€” your app runs however you normally run it (npm run start:dev, node dist/main.js, or in its own Docker container). MeiliSearch is always the only required service here.

services:
  meilisearch:
    image: getmeili/meilisearch:v1.37.0   # โ† pinned version, never :latest
    restart: unless-stopped               # auto-restarts on server reboot or crash
    ports:
      - "7700:7700"                       # exposes port to host
    environment:
      - MEILI_ENV=production              # enforces API key auth on ALL requests
      - MEILI_MASTER_KEY=${MEILISEARCH_MASTER_KEY}
      - MEILI_DB_PATH=/meili_data/data.ms
      - MEILI_DUMP_DIR=/meili_data/dumps
      - MEILI_SNAPSHOT_DIR=/meili_data/snapshots
      - MEILI_SNAPSHOT_INTERVAL_SEC=86400  # auto-snapshot every 24h
    volumes:
      - meilidata:/meili_data              # named volume โ€” works on Windows, Mac, Linux
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:7700/health"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

volumes:
  meilidata:

Enter fullscreen mode Exit fullscreen mode

Why each decision:

  • ports: 7700:7700 โ€” always exposed regardless of topology. NestJS outside Docker reaches via localhost:7700. NestJS on a remote server reaches via <ip>:7700. NestJS inside the same Docker Compose uses the service name meilisearch:7700 internally โ€” but keeping the port exposed is harmless and allows curl/browser access for debugging.
  • Named volume meilidata โ€” not a host path. Works cross-platform with no permission issues on Windows or Mac.
  • restart: unless-stopped โ€” MeiliSearch comes back automatically after machine reboot or Docker Desktop restart.
  • MEILI_SNAPSHOT_INTERVAL_SEC=86400 โ€” automatic daily snapshots inside the volume. Data is always recoverable without manual steps.
  • start_period: 20s โ€” health check grace period so Docker doesn't mark it unhealthy while still booting.

If you also want to run NestJS in Docker (e.g. production server), add this optional app service block to the same file:

# โ”€โ”€ Optional: add this service only if NestJS runs in Docker too โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    env_file:
      - .env
    depends_on:
      meilisearch:
        condition: service_healthy     # waits for MeiliSearch to pass health check
    networks:
      - app-network
    restart: unless-stopped

# โ”€โ”€ Add this network block only if you added the app service above โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
networks:
  app-network:
    driver: bridge

# โ”€โ”€ Also add meilisearch to the same network if you added the app service โ”€โ”€โ”€โ”€โ”€
# Under the meilisearch service, add:
#   networks:
#     - app-network
# And change MEILISEARCH_URL in .env to: http://meilisearch:7700

Enter fullscreen mode Exit fullscreen mode


Step 3 โ€” Dockerfile (Only if NestJS Runs in Docker)

Skip this step entirely if you run NestJS raw with npm run start:dev or node dist/main.js.

FROM node:20-alpine AS builder

WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# โ”€โ”€ Production image โ€” no dev dependencies โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
FROM node:20-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist

EXPOSE 3000
CMD ["node", "dist/main.js"]

Enter fullscreen mode Exit fullscreen mode


Step 4 โ€” Generate Scoped API Keys (One-time Per Environment)

Run this once when you first set up MeiliSearch on any machine. The keys persist in the Docker volume โ€” they survive restarts and reboots.

4a โ€” Start MeiliSearch

docker compose up meilisearch -d

# Wait until healthy
docker compose ps
# meilisearch should show: healthy

Enter fullscreen mode Exit fullscreen mode

Verify it's up from your host machine:

curl http://localhost:7700/health
# โ†’ {"status":"available"}

Enter fullscreen mode Exit fullscreen mode

4b โ€” Run the Key Generation Script

On Mac/Linux or Windows WSL/Git Bash:

Create scripts/create-meili-keys.sh:

#!/bin/bash
set -e

if [ -z "$MEILISEARCH_MASTER_KEY" ]; then
  echo "ERROR: MEILISEARCH_MASTER_KEY is not set."
  echo "Run: export MEILISEARCH_MASTER_KEY=your-key"
  exit 1
fi

MEILI_HOST="http://localhost:7700"

echo ""
echo "=== Creating backend key (full write access โ€” NestJS server only) ==="
curl -s -X POST "${MEILI_HOST}/keys" \
  -H "Authorization: Bearer ${MEILISEARCH_MASTER_KEY}" \
  -H "Content-Type: application/json" \
  --data '{
    "name": "backend-key",
    "description": "NestJS backend โ€” write, index, search. Never expose to frontend.",
    "actions": [
      "documents.add",
      "documents.delete",
      "documents.get",
      "indexes.create",
      "indexes.get",
      "indexes.update",
      "indexes.delete",
      "settings.get",
      "settings.update",
      "tasks.get",
      "search"
    ],
    "indexes": ["*"],
    "expiresAt": null
  }'

echo ""
echo "=== Creating search-only key (safe to expose to frontend clients) ==="
curl -s -X POST "${MEILI_HOST}/keys" \
  -H "Authorization: Bearer ${MEILISEARCH_MASTER_KEY}" \
  -H "Content-Type: application/json" \
  --data '{
    "name": "search-key",
    "description": "Frontend search only โ€” read only, no write access.",
    "actions": ["search"],
    "indexes": ["*"],
    "expiresAt": null
  }'

echo ""
echo "=== Done. Copy the 'key' field values above into your .env ==="
echo "  MEILISEARCH_BACKEND_KEY = key from backend-key response"
echo "  MEILISEARCH_SEARCH_KEY  = key from search-key response"

Enter fullscreen mode Exit fullscreen mode

export MEILISEARCH_MASTER_KEY=your-master-key-here
bash scripts/create-meili-keys.sh

Enter fullscreen mode Exit fullscreen mode

On Windows PowerShell (if you don't have WSL/Git Bash):

$masterKey = "your-master-key-here"

# Backend key
curl.exe -X POST "http://localhost:7700/keys" `
  -H "Authorization: Bearer $masterKey" `
  -H "Content-Type: application/json" `
  --data '{\"name\":\"backend-key\",\"actions\":[\"documents.add\",\"documents.delete\",\"documents.get\",\"indexes.create\",\"indexes.get\",\"indexes.update\",\"indexes.delete\",\"settings.get\",\"settings.update\",\"tasks.get\",\"search\"],\"indexes\":[\"*\"],\"expiresAt\":null}'

# Search key
curl.exe -X POST "http://localhost:7700/keys" `
  -H "Authorization: Bearer $masterKey" `
  -H "Content-Type: application/json" `
  --data '{\"name\":\"search-key\",\"actions\":[\"search\"],\"indexes\":[\"*\"],\"expiresAt\":null}'

Enter fullscreen mode Exit fullscreen mode

Copy the key field from each response into your .env:

MEILISEARCH_BACKEND_KEY=paste-backend-key-here
MEILISEARCH_SEARCH_KEY=paste-search-key-here

Enter fullscreen mode Exit fullscreen mode

Key scoping rules (important):

  • MEILISEARCH_BACKEND_KEY โ€” used by NestJS server code. Full write access. Never sent to browser.
  • MEILISEARCH_SEARCH_KEY โ€” safe for frontend clients. Search-only, read-only.
  • MEILISEARCH_MASTER_KEY โ€” used only in this script. Never appears in NestJS code. Never sent anywhere.
  • Keys are deterministic: same master key โ†’ same key values. Safe to regenerate if you lose them.

Step 5 โ€” Install the JS SDK

npm install meilisearch

Enter fullscreen mode Exit fullscreen mode

Official SDK. Fully typed. No community wrapper needed.


Step 6 โ€” NestJS Integration

Four files make up the search infrastructure. All of them live in src/search/.

src/search/search.config.ts

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class SearchConfig {
  constructor(private readonly configService: ConfigService) {}

  // Reads MEILISEARCH_URL from .env
  // This is the only place the host is read โ€” never hardcoded anywhere else
  get host(): string {
    const url = this.configService.get<string>('MEILISEARCH_URL');
    if (!url) throw new Error('MEILISEARCH_URL is not set in environment');
    return url;
  }

  // Backend key โ€” used for all server-side operations (write + search)
  get backendApiKey(): string {
    const key = this.configService.get<string>('MEILISEARCH_BACKEND_KEY');
    if (!key) throw new Error('MEILISEARCH_BACKEND_KEY is not set in environment');
    return key;
  }

  // Search key โ€” safe to return to frontend for direct client-side search
  get searchApiKey(): string {
    const key = this.configService.get<string>('MEILISEARCH_SEARCH_KEY');
    if (!key) throw new Error('MEILISEARCH_SEARCH_KEY is not set in environment');
    return key;
  }
}

Enter fullscreen mode Exit fullscreen mode

src/search/search.service.ts

This is the wrapper around the MeiliSearch client. All other parts of your app go through this service โ€” they never instantiate their own client.

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Meilisearch, Index, SearchParams, SearchResponse, Settings } from 'meilisearch';
import { SearchConfig } from './search.config';

@Injectable()
export class SearchService implements OnModuleInit {
  private readonly logger = new Logger(SearchService.name);
  private client: Meilisearch;

  constructor(private readonly config: SearchConfig) {}

  onModuleInit() {
    // host resolves from MEILISEARCH_URL in .env
    // works whether NestJS is in Docker, raw on Windows/Mac/Linux, or on a remote server
    this.client = new Meilisearch({
      host:   this.config.host,
      apiKey: this.config.backendApiKey,
    });

    this.logger.log(`MeiliSearch client initialized โ†’ ${this.config.host}`);
  }

  // โ”€โ”€โ”€ Health โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async ping(): Promise<boolean> {
    try {
      await this.client.health();
      return true;
    } catch {
      return false;
    }
  }

  // โ”€โ”€โ”€ Index access โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  getIndex<T>(indexName: string): Index<T> {
    return this.client.index<T>(indexName);
  }

  // โ”€โ”€โ”€ Documents โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async addDocuments<T extends Record<string, unknown>>(
    indexName: string,
    documents: T[],
    primaryKey = 'id',
  ) {
    const task = await this.client.index<T>(indexName).addDocuments(documents, { primaryKey });
    this.logger.log(`Enqueued addDocuments โ†’ ${indexName} (task ${task.taskUid})`);
    return task;
  }

  async updateDocuments<T extends Record<string, unknown>>(
    indexName: string,
    documents: T[],
    primaryKey = 'id',
  ) {
    const task = await this.client.index<T>(indexName).updateDocuments(documents, { primaryKey });
    this.logger.log(`Enqueued updateDocuments โ†’ ${indexName} (task ${task.taskUid})`);
    return task;
  }

  async deleteDocument(indexName: string, documentId: string | number) {
    const task = await this.client.index(indexName).deleteDocument(documentId);
    this.logger.log(`Enqueued deleteDocument โ†’ ${indexName}/${documentId} (task ${task.taskUid})`);
    return task;
  }

  async deleteDocuments(indexName: string, documentIds: Array<string | number>) {
    const task = await this.client.index(indexName).deleteDocuments(documentIds);
    this.logger.log(`Enqueued deleteDocuments โ†’ ${indexName} (${documentIds.length} docs, task ${task.taskUid})`);
    return task;
  }

  // โ”€โ”€โ”€ Search โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async search<T>(
    indexName: string,
    query: string,
    params?: SearchParams,
  ): Promise<SearchResponse<T>> {
    return this.client.index<T>(indexName).search(query, params);
  }

  // โ”€โ”€โ”€ Settings โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async updateIndexSettings(indexName: string, settings: Settings) {
    const task = await this.client.index(indexName).updateSettings(settings);
    this.logger.log(`Enqueued updateSettings โ†’ ${indexName} (task ${task.taskUid})`);
    return task;
  }

  // โ”€โ”€โ”€ Tasks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async waitForTask(taskUid: number, timeoutMs = 30000) {
    return this.client.waitForTask(taskUid, { timeoutInMs: timeoutMs });
  }

  // โ”€โ”€โ”€ Backup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async createDump() {
    const task = await this.client.createDump();
    this.logger.log(`Dump creation enqueued (task ${task.taskUid})`);
    return task;
  }

  // โ”€โ”€โ”€ Raw client (escape hatch for SDK features not wrapped above) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  getClient(): Meilisearch {
    return this.client;
  }
}

Enter fullscreen mode Exit fullscreen mode

src/search/search.module.ts

import { Global, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { SearchConfig } from './search.config';
import { SearchService } from './search.service';

@Global()   // any module can inject SearchService without re-importing SearchModule
@Module({
  imports:   [ConfigModule],
  providers: [SearchConfig, SearchService],
  exports:   [SearchConfig, SearchService],
})
export class SearchModule {}

Enter fullscreen mode Exit fullscreen mode

src/search/index.ts

export * from './search.module';
export * from './search.service';
export * from './search.config';
export * from './indexes';

Enter fullscreen mode Exit fullscreen mode


Step 7 โ€” Per-Index Files (One Per Index)

Each index gets its own file. Define searchable/filterable/sortable attributes here. These settings are applied on every app startup via OnModuleInit โ€” idempotent, safe to run repeatedly.

src/search/indexes/product.index.ts

This is an example. Replace product with whatever your domain is โ€” investments, accounts, transactions, whatever.

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { SearchService } from '../search.service';

export const PRODUCT_INDEX = 'products';

export interface ProductDocument {
  id:          string;
  name:        string;
  description: string;
  brand:       string;
  category:    string;
  price:       number;
  inStock:     boolean;
  createdAt:   string;
}

@Injectable()
export class ProductIndex implements OnModuleInit {
  private readonly logger = new Logger(ProductIndex.name);

  constructor(private readonly searchService: SearchService) {}

  async onModuleInit() {
    await this.applySettings();
  }

  private async applySettings() {
    try {
      const task = await this.searchService.updateIndexSettings(PRODUCT_INDEX, {
        // Only fields users will search โ€” controls relevance and index size
        searchableAttributes: ['name', 'description', 'brand', 'category'],

        // Fields available for .filter() queries
        filterableAttributes: ['category', 'brand', 'price', 'inStock'],

        // Fields available for .sort() queries
        sortableAttributes: ['price', 'createdAt', 'name'],

        rankingRules: [
          'words',      // more query words matched = higher rank
          'typo',       // fewer typos = higher rank
          'proximity',  // query words closer together = higher rank
          'attribute',  // earlier searchableAttribute = higher rank
          'sort',       // user-specified sort order
          'exactness',  // exact match = higher rank
        ],

        typoTolerance: {
          enabled: true,
          minWordSizeForTypos: {
            oneTypo:  4,   // allow 1 typo for words >= 4 chars
            twoTypos: 8,   // allow 2 typos for words >= 8 chars
          },
        },

        pagination: {
          maxTotalHits: 1000,
        },
      });

      await this.searchService.waitForTask(task.taskUid);
      this.logger.log(`Settings applied โ†’ ${PRODUCT_INDEX}`);
    } catch (error) {
      // Log but do not throw โ€” app still starts even if settings fail
      this.logger.error(`Failed to apply settings โ†’ ${PRODUCT_INDEX}`, (error as Error).stack);
    }
  }

  // โ”€โ”€โ”€ Type-safe query methods โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async searchProducts(
    query: string,
    options?: {
      category?: string;
      brand?:    string;
      inStock?:  boolean;
      maxPrice?: number;
      page?:     number;
    },
  ) {
    const filters: string[] = [];
    if (options?.category)               filters.push(`category = "${options.category}"`);
    if (options?.brand)                  filters.push(`brand = "${options.brand}"`);
    if (options?.inStock !== undefined)  filters.push(`inStock = ${options.inStock}`);
    if (options?.maxPrice !== undefined) filters.push(`price <= ${options.maxPrice}`);

    return this.searchService.search<ProductDocument>(PRODUCT_INDEX, query, {
      filter:                filters.join(' AND '),
      hitsPerPage:           20,
      page:                  options?.page ?? 1,
      attributesToHighlight: ['name', 'description'],
    });
  }

  async indexProducts(products: ProductDocument[]) {
    return this.searchService.addDocuments(PRODUCT_INDEX, products, 'id');
  }

  async removeProduct(productId: string) {
    return this.searchService.deleteDocument(PRODUCT_INDEX, productId);
  }
}

Enter fullscreen mode Exit fullscreen mode

src/search/indexes/index.ts

export * from './product.index';
// export * from './[feature].index';  โ† add each new index here

Enter fullscreen mode Exit fullscreen mode


Step 8 โ€” Wire into AppModule

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { SearchModule } from './search';
import { ProductIndex } from './search/indexes';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    SearchModule,
    // ... rest of your modules
  ],
  providers: [
    ProductIndex,   // registers the OnModuleInit settings sync
  ],
})
export class AppModule {}

Enter fullscreen mode Exit fullscreen mode


Step 9 โ€” Start Everything

Scenario A: NestJS raw on same machine, MeiliSearch in Docker

# 1. Start MeiliSearch (Docker Desktop must be running on Windows)
docker compose up meilisearch -d

# 2. Verify it's healthy
curl http://localhost:7700/health
# โ†’ {"status":"available"}

# 3. Start NestJS normally
npm run start:dev
# or
npm run start:prod

Enter fullscreen mode Exit fullscreen mode

Your .env has MEILISEARCH_URL=http://localhost:7700.

Scenario B: Both NestJS and MeiliSearch in Docker Compose

docker compose up --build -d
docker compose ps   # both services should show healthy/running

Enter fullscreen mode Exit fullscreen mode

Your .env has MEILISEARCH_URL=http://meilisearch:7700.

Scenario C: NestJS on one server, MeiliSearch on a separate server

# On the MeiliSearch server:
docker compose up meilisearch -d

# On the NestJS server โ€” .env has:
# MEILISEARCH_URL=http://<MEILISEARCH_SERVER_IP>:7700
npm run start:prod

Enter fullscreen mode Exit fullscreen mode

Firewall note for Scenario C: Port 7700 on the MeiliSearch server must allow inbound TCP connections from the NestJS server's IP. Restrict it to only that IP โ€” do not open 7700 to the public internet.


Step 10 โ€” Adding a New Index (Checklist)

Every time you add a new searchable feature, touch these files in order:

1. Create src/search/indexes/my-feature.index.ts

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { SearchService } from '../search.service';

export const MY_FEATURE_INDEX = 'my-feature';

export interface MyFeatureDocument {
  id:    string;
  title: string;
  body:  string;
  // only fields the search actually needs
}

@Injectable()
export class MyFeatureIndex implements OnModuleInit {
  private readonly logger = new Logger(MyFeatureIndex.name);

  constructor(private readonly searchService: SearchService) {}

  async onModuleInit() {
    try {
      const task = await this.searchService.updateIndexSettings(MY_FEATURE_INDEX, {
        searchableAttributes: ['title', 'body'],
        filterableAttributes: ['status', 'authorId'],
        sortableAttributes:   ['createdAt'],
      });
      await this.searchService.waitForTask(task.taskUid);
      this.logger.log(`Settings applied โ†’ ${MY_FEATURE_INDEX}`);
    } catch (error) {
      this.logger.error(`Settings failed โ†’ ${MY_FEATURE_INDEX}`, (error as Error).stack);
    }
  }

  async search(query: string) {
    return this.searchService.search<MyFeatureDocument>(MY_FEATURE_INDEX, query);
  }

  async index(documents: MyFeatureDocument[]) {
    return this.searchService.addDocuments(MY_FEATURE_INDEX, documents, 'id');
  }
}

Enter fullscreen mode Exit fullscreen mode

2. Add barrel export in src/search/indexes/index.ts:

export * from './my-feature.index';

Enter fullscreen mode Exit fullscreen mode

3. Register in AppModule providers:

providers: [MyFeatureIndex],

Enter fullscreen mode Exit fullscreen mode

4. Export from your feature module if other modules need to inject it:

exports: [MyFeatureIndex],

Enter fullscreen mode Exit fullscreen mode


The Full End-to-End Architecture (Production Pattern)

When you're building something real, you don't want MeiliSearch writes to be synchronous blocking calls in your main request path. If MeiliSearch has a hiccup, you don't want your POST /investments endpoint to fail.

Here's the pattern that handles this correctly:

1. SearchOutboxHelper โ€” Write Events Atomically with Your Entity

Why: If MeiliSearch crashes or is temporarily unavailable, your app must still function. By using the Outbox Pattern, you write the search event into PostgreSQL (your source of truth) within the same transaction as the entity creation. A background worker then safely syncs it to MeiliSearch.

Inside your repository, wrap Prisma queries in a $transaction and call the outbox helper:

import { writeSearchOutbox } from 'src/search/helpers/search-outbox.helper';

async createInvestment(data: any, userId: string) {
  return this.prisma.$transaction(async (tx) => {
    // 1. Create the entity
    const investment = await tx.investments.create({ data });

    // 2. Queue for Search Indexing (Atomic โ€” same transaction)
    await writeSearchOutbox(tx, {
      entity_type: 'investments',
      entity_id: investment.id,
      action: 'UPSERT',
      user_id: userId,
      payload: { ...investment },
    });

    return investment;
  });
}

Enter fullscreen mode Exit fullscreen mode

2. BullMQ Worker โ€” Queue Processing

The SearchQueueService listens for PostgreSQL AuditLog outbox records and enqueues them to BullMQ (search-sync queue). The SearchSyncProcessor consumes these jobs, pushes the payload to MeiliSearch via SearchService, and marks the record as search_synced = true.

If MeiliSearch is down, the jobs stay in the queue and retry. Your core app keeps working.

3. Search Controller โ€” Tenant-Isolated API Route

We don't expose the MeiliSearch search key directly to the frontend โ€” we want backend-level tenant isolation (filter by user_id on every query so users can't see each other's data):

@Get()
@Throttle({ default: { limit: 120, ttl: 60000 } }) // Higher limit for fast debounced typing
async search(
  @GetAdmin('id') userId: string,
  @Query('q') query: string,
  @Query('service') service: string, // e.g. 'investments'
) {
  return this.searchService.search(service, query, { filter: `user_id = "${userId}"` });
}

Enter fullscreen mode Exit fullscreen mode

4. Frontend Integration โ€” Global Search Bar

const handleSearch = useDebouncedCallback(async (query: string) => {
  // Fire requests concurrently across multiple indices
  const [investments, accounts] = await Promise.all([
    axios.get(`/xam/search?q=${query}&service=investments`),
    axios.get(`/xam/search?q=${query}&service=accounts`)
  ]);
  setResults([...investments.data.hits, ...accounts.data.hits]);
}, 300); // 300ms debounce

Enter fullscreen mode Exit fullscreen mode

The @Throttle decorator on the controller is why this works without 429s. Standard NestJS throttler defaults would kill this immediately at 4 concurrent requests per keystroke.


Backup and Recovery

Dumps โ€” Use for Version Migrations

Portable, human-readable export. Works across MeiliSearch versions.

# Create a dump
curl -X POST http://localhost:7700/dumps \
  -H "Authorization: Bearer ${MEILISEARCH_BACKEND_KEY}"
# โ†’ returns { "taskUid": 1 }

# Poll until status = "succeeded"
curl http://localhost:7700/tasks/1 \
  -H "Authorization: Bearer ${MEILISEARCH_BACKEND_KEY}"

# Dump file is at /meili_data/dumps/ inside the Docker volume

Enter fullscreen mode Exit fullscreen mode

Snapshots โ€” Use for Fast Rollbacks

Binary-exact copy. Faster to restore than dumps but version-specific โ€” do NOT use across MeiliSearch version upgrades.

Daily auto-snapshots are already configured in the docker-compose.yml above via MEILI_SNAPSHOT_INTERVAL_SEC=86400. Snapshots live at /meili_data/snapshots/ inside the volume.

Upgrading MeiliSearch Versions

# Step 1: Create a dump from the running instance
curl -X POST http://localhost:7700/dumps \
  -H "Authorization: Bearer ${MEILISEARCH_BACKEND_KEY}"

# Step 2: Wait for task to succeed, note the dump filename

# Step 3: Update docker-compose.yml
#   getmeili/meilisearch:v1.37.0  โ†’  getmeili/meilisearch:vX.Y.Z

# Step 4: Temporarily add import command to docker-compose.yml meilisearch service:
#   command: ["meilisearch", "--import-dump=/meili_data/dumps/YOUR_DUMP_FILE.dump"]

# Step 5: Start the new version
docker compose up meilisearch -d

# Step 6: Verify data is intact, then remove the --import-dump command line
# Step 7: Restart normally
docker compose up meilisearch -d --force-recreate

Enter fullscreen mode Exit fullscreen mode


Verify Everything is Connected

# Health check (from host machine โ€” always localhost:7700)
curl http://localhost:7700/health
# โ†’ {"status":"available"}

# List API keys (uses master key)
curl http://localhost:7700/keys \
  -H "Authorization: Bearer ${MEILISEARCH_MASTER_KEY}"

# Verify backend key works
curl http://localhost:7700/indexes \
  -H "Authorization: Bearer ${MEILISEARCH_BACKEND_KEY}"

# Check logs
docker compose logs meilisearch
docker compose logs app   # only if NestJS is in Docker

Enter fullscreen mode Exit fullscreen mode


Key API Reference (meilisearch JS SDK)

Quick cheat sheet for the most common operations:

import { Meilisearch } from 'meilisearch';

const client = new Meilisearch({
  host:   process.env.MEILISEARCH_URL,        // from .env โ€” never hardcoded
  apiKey: process.env.MEILISEARCH_BACKEND_KEY,
});

const index = client.index('products');

// Add / update documents
await index.addDocuments(docs, { primaryKey: 'id' });
await index.updateDocuments(docs, { primaryKey: 'id' });

// Delete
await index.deleteDocument('doc-id-123');
await index.deleteDocuments(['id1', 'id2', 'id3']);
await index.deleteAllDocuments();

// Search
const results = await index.search('wireless headphones', {
  filter:                'category = "Electronics" AND price < 200',
  sort:                  ['price:asc'],
  hitsPerPage:           20,
  page:                  1,
  attributesToHighlight: ['name', 'description'],
});
// results.hits            โ€” matched documents
// results.totalHits       โ€” total count
// results.processingTimeMs โ€” query latency in ms

// Settings (idempotent โ€” safe to call on every startup)
await index.updateSettings({
  searchableAttributes: ['name', 'description'],
  filterableAttributes: ['category', 'price'],
  sortableAttributes:   ['price', 'createdAt'],
});

// All write operations are async โ€” poll the task to confirm
const task   = await index.addDocuments(docs);
const result = await client.tasks.waitForTask(task.taskUid); // v0.40+ syntax
// result.status: 'succeeded' | 'failed' | 'enqueued' | 'processing'

// Health
const health = await client.health();
// health.status: 'available'

Enter fullscreen mode Exit fullscreen mode


Common Mistakes Reference

// โŒ Hardcoding the host in application code
const client = new Meilisearch({ host: 'http://localhost:7700' });
// โœ… Always read from environment
const client = new Meilisearch({ host: process.env.MEILISEARCH_URL });

// โŒ Using master key in application code
const client = new Meilisearch({ apiKey: process.env.MEILISEARCH_MASTER_KEY });
// โœ… Use the scoped backend key
const client = new Meilisearch({ apiKey: process.env.MEILISEARCH_BACKEND_KEY });

// โŒ Using :latest Docker image tag
image: getmeili/meilisearch:latest
// โœ… Always pin to a specific version
image: getmeili/meilisearch:v1.37.0

// โŒ MEILI_ENV not set โ€” anyone can hit the API without a key
// โœ… Always set
- MEILI_ENV=production

// โŒ Using MEILISEARCH_URL=http://meilisearch:7700 when NestJS runs outside Docker
//    Docker service names only resolve inside Docker networks
// โœ… Use localhost:7700 when NestJS runs raw on the same machine as Docker

// โŒ Using MEILISEARCH_URL=http://localhost:7700 when NestJS runs inside Docker
//    localhost inside a container = the container itself, not the host
// โœ… Use http://meilisearch:7700 (service name) when both are in same Docker Compose

// โŒ Opening port 7700 to the public internet when MeiliSearch is on a separate server
// โœ… Restrict firewall to allow 7700 only from the NestJS server's IP

// โŒ Host-path volume mounts โ€” permission/performance issues on Windows and Mac
volumes:
  - ./meili_data:/meili_data
// โœ… Named Docker volumes โ€” works everywhere
volumes:
  - meilidata:/meili_data

// โŒ Not setting searchableAttributes โ€” MeiliSearch indexes all fields by default
//    Causes large index sizes and slower search on documents with many fields
// โœ… Always set searchableAttributes explicitly in per-index OnModuleInit

// โŒ Upgrading Docker image version without creating a dump first
// โœ… Always dump โ†’ upgrade โ†’ import

Enter fullscreen mode Exit fullscreen mode


Wrapping Up

That's the full production setup โ€” Docker config, key management, NestJS service layer, per-index files, the outbox pattern for resilient indexing, backup/recovery, and the common mistakes that'll waste your afternoon.

The thing I actually like about MeiliSearch is that it doesn't fight you. The docker-compose.yml is 30 lines. The JS SDK is properly typed. The search results are genuinely good out of the box. For a Cmd+K style search across multiple entity types in a NestJS app, this is the stack I'd reach for every time now.

If you have questions, drop them in the comments. If you ran into a specific deployment scenario I didn't cover, let me know.