DEV Community

Ganesh Joshi
Ganesh Joshi

Posted on

Prompt Injection Defenses for LLM Gateways

This post was created with AI assistance and reviewed for accuracy before publishing.

Hackers love prompt injection. It is the easiest way to break an AI app. They paste instructions like "ignore previous steps" into your search box. If you do not filter this, your application will expose internal data.

I tried building a gateway filter in Node.js. It runs before sending the payload to the API. It scans user text for typical jailbreak patterns.

We can intercept the request and check the text content. Here is a simple middleware validator.

// Chronological steps to filter prompt inputs
function validateInputPrompt(userInput) {
  // 1. Convert input to lowercase to prevent evasion
  const normalized = userInput.toLowerCase();

  // 2. Define known injection markers
  const redFlags = ["ignore instructions", "system override", "you are now unrestricted"];

  // 3. Match and reject
  for (const flag of redFlags) {
    if (normalized.includes(flag)) {
      throw new Error("Potential prompt injection attempt blocked.");
    }
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

This simple check catches common exploits. It does not replace a good model-level guardrail, but it adds a fast layer of defense. Keep your system prompt separated from user variables in your API payload.

Top comments (0)