How to secure Cursor: best practices and hooks
How to secure Cursor: Privacy Mode, .cursorignore, MCP tokens and hooks, then lock down the app it built before deployment. Includes a free scan.
Cursor gives you real code in your own repository, which means you are responsible for the parts a hosted builder would hide. This guide covers both halves: locking down Cursor itself, and checking the app it built before you deploy. Start with the Cursor app secrets checklist if keys are your main worry.
How to secure Cursor: the short checklist
- Turn on Privacy Mode, so your code is not used for training.
- Add a
.cursorignorethat lists.envand other secret files, and remember it does not cover the terminal or MCP tools. - Use
${env:NAME}in.cursor/mcp.jsoninstead of pasting tokens, and install only MCP servers you trust. - Do not use Run Everything. Cursor calls its run modes best-effort guardrails, not a security boundary, so read what the agent asks to run.
- Add a
beforeReadFilehook that denies secret files, withfailClosed: true. - Review what the agent changes with git, and review changes to
.cursor/files like code. - Keep live keys out of the repo and off your laptop. Your local
.envholds test keys only; live keys go in your host's environment settings. - Scan the deployed app with the free scan before you share the link.
Cursor secrets: where keys leak
- A committed
.envfile. The file may be gone from your folder but still sit in git history. - A
NEXT_PUBLIC_orVITE_name on a secret. Those values are sent to every visitor's browser. - A key pasted into
.cursor/mcp.json, a chat message or a prompt. Use environment references instead. - The agent reading
.env..cursorignoreblocks the agent, Tab and@mentions, but Cursor says terminal and MCP tools are not covered, so keep live keys out of local files where you can.
Cursor security best practices
Cursor's own security guidance starts with a plain warning: AI can behave unexpectedly because of prompt injection, hallucinations and other issues, and its defaults are worth keeping on.
Turn on Privacy Mode
Privacy Mode can be switched on in Cursor's settings (or by a team admin). When it is on, Cursor says your code is never used for training by Cursor or its model providers. Cursor documents Privacy Mode as a training and data-handling setting, not as a way to control which files the agent reads. That is what .cursorignore and hooks are for.
Block secret files with .cursorignore
Create a .cursorignore in your project root. It uses .gitignore syntax, so a few lines are enough:
.env
.env.*
Cursor blocks files listed there from the agent and Tab, and from @ mentions. Cursor's docs give two limits: the terminal and the MCP tools the agent uses cannot be blocked by .cursorignore, and complete protection is not guaranteed because of LLM unpredictability. You can also set ignore patterns for all projects in your user settings. Treat the file as a seatbelt, not a vault: the safest key is one that is not on your disk.
Keep MCP tokens out of the file
Cursor warns that MCP servers can access external services and run code on your behalf. Its docs advise installing only servers from trusted developers and using restricted API keys with minimal permissions. In .cursor/mcp.json (or ~/.cursor/mcp.json for all projects), Cursor resolves variables in command, args, env, url and headers, so a token can come from your environment:
{
"mcpServers": {
"my-server": {
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer ${env:MY_SERVER_TOKEN}" }
}
}
}
The project file lives in your repository, so a pasted token can be committed with it. The reference only names a variable.
Know your run modes
Cursor's security page says sensitive actions need your approval by default, and that includes terminal commands, MCP connections and each MCP tool call. Its run-modes page describes three modes: Auto-review, the recommended default, where a sandbox and a classifier decide what runs without asking; Allowlist, where only actions on your allowlist run without asking; and Run Everything, where every tool call runs automatically with no sandbox and no classifier. Cursor calls its run modes best-effort guardrails rather than a hard security boundary. If a database URL or a payment key is anywhere nearby, avoid Run Everything and read what the agent asks to run.
Be careful with unfamiliar repositories
Cursor's docs say workspace trust is disabled by default and that restricted mode breaks AI features. For a repository you do not trust, the docs' own advice is to use a basic text editor instead.
Review what the agent changes
Per Cursor's docs, agents can modify workspace files without approval (configuration files excepted), and reading files and searching code do not need approval either. So commit before a big agent run, read the diff afterwards, and look for new network calls, new dependencies and any key that appeared in a file.
Review rules files like code
Project rules live in .cursor/rules and can also be an AGENTS.md in the project root. Cursor's docs describe project rules as version-controlled, so a change to them shows up in a pull request. Read it there. Cursor also says AI guidance should not be your only security control, so a rule is no substitute for ignore files, hooks and review.
Secrets management for a Cursor app
- Keep a
.envfile for test or development keys only, listed in.gitignoreand in.cursorignore. - Put live keys in your host's environment settings (Vercel, Netlify, Fly and so on), never in the repository.
- Keep secrets in server-only code. Anything the browser needs must be a public key by design.
- If a key was ever in git, a screenshot or a prompt, make a new one in that service. The old one is already out.
Full walkthrough: Secrets in a Cursor app: .env, .cursorignore and git history.
Cursor hooks security
Cursor describes hooks as a way to observe, control and extend the agent loop with custom scripts. A command hook is a script that receives JSON on stdin and answers with JSON on stdout. That lets you enforce a rule in a script instead of hoping a prompt or a rules file is followed.
Where they live. Project hooks go in .cursor/hooks.json; your personal hooks go in ~/.cursor/hooks.json. Enterprise and team hooks, where your organization uses them, take priority over both. Project hooks run from the project root, so a path looks like .cursor/hooks/check.sh. Cursor reloads the file on save and has a Hooks output channel that shows errors.
Events. The agent events include preToolUse, beforeShellExecution, beforeMCPExecution, beforeReadFile, afterFileEdit, beforeSubmitPrompt and stop. Tab has its own pair, beforeTabFileRead and afterTabFileEdit. The docs list more; check them for your version.
Allow, deny, ask.
beforeReadFilecan answerallowordeny, so a sensitive file is not sent to the model.beforeShellExecutionandbeforeMCPExecutioncan answerallow,denyoraskbefore a command or MCP tool runs, with auser_messagefor you and anagent_messagefor the agent.- Exiting with code
2blocks the action, the same as answeringdeny. - For
preToolUse,askis accepted by the schema but not enforced today.
Failing closed. A hook that crashes, times out or exits with a code other than 2 lets the action through by default. Set "failClosed": true on hooks that guard secrets, so a failure blocks instead. Cursor also says invalid JSON, or a reply that does not match the hook's schema, blocks a file read.
Project or user hooks. Project hooks are checked into version control with your project and run in a trusted workspace, so treat a change to .cursor/hooks.json or to a script in .cursor/hooks/ in a pull request like a change to executable code. User hooks follow you to every project and stay out of the repository.
A small example: deny reads of .env files
Save this as .cursor/hooks/block-dotenv.sh and make it executable (chmod +x). It is a shell script for macOS or Linux; on Windows, Cursor runs hook commands through PowerShell, and with failClosed: true a script that cannot run blocks every file read.
#!/bin/sh
input=$(cat)
if printf '%s' "$input" | grep -Eq '"file_path" *: *"([^"]*/)?\.env[^"/]*"'; then
echo '{"permission":"deny","user_message":"Blocked: the agent may not read .env files."}'
else
echo '{"permission":"allow"}'
fi
Then register it in .cursor/hooks.json:
{
"version": 1,
"hooks": {
"beforeReadFile": [
{ "command": ".cursor/hooks/block-dotenv.sh", "failClosed": true }
]
}
}
The script reads the file_path field Cursor sends to beforeReadFile and denies any file name that starts with .env, including .env.local and .env.example. Ask the agent to open your .env and check the Hooks output channel to confirm it ran. It only sees file reads: terminal commands go through beforeShellExecution, so add a second hook there. Hooks are a guardrail, not a promise. Read what Cursor documents for your version at cursor.com/docs before you rely on one.
Secure Cursor deployment
Cursor writes the code; shipping it safely is still on you. Work through these checks before you deploy. The prompts can be pasted into Cursor's chat.
1. Keep .env out of git
Check that .env and .env.local are in .gitignore, and that they were never committed:
git log --all --oneline -- .env .env.local
If that prints anything, the secrets are in your history even if the file is gone. Rotate those keys. Check your history with the command above before you launch.
2. Put live keys in your host, not in files
Set production values in your host's environment settings and keep a test-only set locally. Use different keys for preview deployments and production, so a leaked preview link does not expose the live account.
3. Watch the public prefixes
In Next.js, variables starting with NEXT_PUBLIC_ are sent to the browser. In Vite, it is VITE_. Never put a secret key behind those names. Our post on API keys in your JavaScript shows how to find them in the built site.
Search the project for environment variables starting with NEXT_PUBLIC_ or VITE_ and tell me which ones contain secrets (secret API keys, service role keys, private tokens). Rename them without the prefix and move the code that uses them to server-only code.
4. Protect every API route
AI-generated routes often fetch data for whoever asks. Each route that returns or changes user data must check the session on the server.
Review every file in app/api (or pages/api). For each route that returns or changes user data, add a server-side check that the caller is signed in and owns the data, returning 401 or 403 otherwise. Do not trust user ids sent in the request body.
5. Lock down CORS and headers
Do not set Access-Control-Allow-Origin: * on routes that use cookies or tokens. Add security headers in next.config (HSTS, X-Frame-Options, a Content-Security-Policy).
6. If you use Supabase
Turn on Row Level Security for each table and never use the service_role key in client code. See our Supabase RLS post. New tables also need an explicit grant, which is covered in the Supabase October 30 grants change.
7. Run the free scan on the live URL
Run the free scan on your preview or production URL to see your score and problem count. It looks at the app from the outside, the way a stranger would. The Full Scan then gives each finding a prompt written for Cursor, ready to paste into the chat. The 10-minute pre-launch security checklist covers the rest.
Common questions about Cursor security
Is Cursor safe to use for production code?
That depends on how you review it. Cursor's own docs say AI can behave unexpectedly because of prompt injection and hallucinations, so the output needs the same review as code from a new teammate. Avoid Run Everything, read the diff, keep live keys out of the repository, and scan the deployed app.
Can Cursor hooks block the agent from reading .env?
Yes, for file reads. Cursor documents a beforeReadFile hook that can answer deny, so a sensitive file is not sent to the model. Set failClosed: true so a crashing script blocks instead of letting the read through. Shell commands need their own beforeShellExecution hook.
Is .cursorignore enough to protect my keys?
No. It blocks the agent, Tab and @ mentions from ignored files, but Cursor says the terminal and MCP tools cannot be blocked by it and that complete protection is not guaranteed. Combine it with a hook and keep live keys off your machine.
Does Privacy Mode stop Cursor from reading my .env?
No. Privacy Mode is about training: Cursor says that when it is on, your code is never used for training by Cursor or its model providers. Which files the agent can read is controlled by .cursorignore, hooks and your own habits.
The Friday leak report
One short email a week: the newest ways AI-built apps leak data, and the one-line fix for each. No spam, unsubscribe any time.