continuedev/nextjs-security-assistant icon
public
Published on 4/4/2025
Next.js Security Assistant

This assistant helps you write secure Next.js applications or audit the code of existing Next.js applications.

Rules
Prompts
Models
Context
anthropic Claude 3.7 Sonnet model icon

Claude 3.7 Sonnet

anthropic

200kinput·8.192koutput
anthropic Claude 3.5 Sonnet model icon

Claude 3.5 Sonnet

anthropic

200kinput·8.192koutput
mistral Codestral model icon

Codestral

mistral

voyage voyage-code-3 model icon

voyage-code-3

voyage

voyage Voyage AI rerank-2 model icon

Voyage AI rerank-2

voyage

# Next.js Security Best Practices

## Data Validation and Input Handling
- **Always validate user inputs with schemas**
  - ❌ Directly using req.body in API handlers without validation
  - ✅ Using schema validation libraries to validate request bodies before processing them

- **Sanitize rendered content**
  - ❌ Using dangerouslySetInnerHTML with unsanitized content
  - ✅ Using a sanitization library to clean HTML or avoiding direct HTML insertion

- **Be careful with dynamic imports**
  - ❌ Using unvalidated user input for dynamic imports or file paths
  - ✅ Strictly validating and limiting what can be dynamically imported

## API Routes and Server Security
- **Separate API route handlers from page components**
  - ❌ Using fetch with sensitive operations directly in client components
  - ✅ Creating separate API route handlers and calling them from client components

- **Secure API routes with proper authentication**
  - ❌ Creating API routes that don't verify auth status before performing operations
  - ✅ Checking auth status at the beginning of API handlers and returning 401/403 when needed

- **Implement proper CSRF protection**
  - ❌ Creating custom API endpoints without CSRF tokens for state-changing operations
  - ✅ Using form actions with built-in CSRF protection or adding CSRF tokens to custom APIs

- **Use proper error handling in API routes**
  - ❌ Returning full error details: `return res.status(500).json({ error: err.stack })`
  - ✅ Logging detailed errors server-side but returning generic messages to clients

- **Implement rate limiting**
  - ❌ Allowing unlimited requests to sensitive endpoints
  - ✅ Using rate limiting middleware or implementing custom rate limiting

## Environment and Configuration Security
- **Use environment variables correctly**
  - ❌ Adding API keys with NEXT_PUBLIC_ prefix or hardcoding them in client components
  - ✅ Using process.env.API_KEY in server components or API routes only

- **Set appropriate Security Headers**
  - ❌ Leaving default security headers without customization
  - ✅ Using the Next.js headers configuration to set appropriate security policies

## Data Storage and Transmission
- **Avoid client-side secrets in redirects**
  - ❌ Redirecting with sensitive data in query params: `router.push(/success?token=${token})`
  - ✅ Using cookies or session storage for sensitive data during redirects

- **Secure cookies configuration**
  - ❌ Setting cookies without security attributes
  - ✅ Using appropriate httpOnly, secure, and sameSite attributes for sensitive data

## Content and File Security
- **Beware of metadata injection**
  - ❌ Using unvalidated user input directly in page metadata
  - ✅ Sanitizing or validating any user-provided data used in metadata

- **Secure file uploads**
  - ❌ Accepting any file upload without validation
  - ✅ Implementing strict validation for file types, sizes, and content

## Advanced Protections
- **Protect against prototype pollution**
  - ❌ Deep merging objects from untrusted sources without sanitization
  - ✅ Using Object.create(null) or dedicated libraries for safe object merging
XSS Preventionhttps://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
CSRF Protectionhttps://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
Next.js Securityhttps://nextjs.org/blog/security-nextjs-server-components-actions
Web Securityhttps://developer.mozilla.org/en-US/docs/Web/Security
API Securityhttps://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
Next.js Authenticationhttps://nextjs.org/docs/authentication
OWASP Top 10https://owasp.org/www-project-top-ten/

Prompts

Learn more
Next.js Security Review
Check for any potential security vulnerabilities in your code
Please review my Next.js code with a focus on security issues.

Use the below as a starting point, but consider any other potential issues

You do not need to address every single area below, only what is relevant to the user's code.

1. Data Exposure:
- Verify Server Components aren't passing full database objects to Client Components
- Check for sensitive data in props passed to 'use client' components
- Look for direct database queries outside a Data Access Layer
- Ensure environment variables (non NEXT_PUBLIC_) aren't exposed to client

2. Server Actions ('use server'):
- Confirm input validation on all parameters
- Verify user authentication/authorization checks
- Check for unencrypted sensitive data in .bind() calls

3. Route Safety:
- Validate dynamic route parameters ([params])
- Check custom route handlers (route.ts) for proper CSRF protection
- Review middleware.ts for security bypass possibilities

4. Data Access:
- Ensure parameterized queries for database operations
- Verify proper authorization checks in data fetching functions
- Look for sensitive data exposure in error messages

Key files to focus on: files with 'use client', 'use server', route.ts, middleware.ts, and data access functions.
Authentication review
Reviews authentication implementation
Examine this authentication code for security issues. Ask questions about the auth flow, user management, and session handling. Consider common attack scenarios.
Data validation check
Checks input validation and sanitization
Analyze this code for data validation vulnerabilities. Ask about data sources, validation rules, and how the data is used throughout the application.
Environment variables
Checks environment variable usage
Review how environment variables are used. Ask questions about sensitive data handling, deployment practices, and potential exposure points.
Middleware inspection
Reviews middleware security
Examine this middleware for security concerns. Ask about its purpose, what it protects, and how it could potentially be bypassed.
API route inspection
Analyzes API routes for security issues
Review this API route for security vulnerabilities. Ask questions about the context, data flow, and potential attack vectors. Be thorough in your investigation.

Context

Learn more
@diff
Reference all of the changes you've made to your current branch
@codebase
Reference the most relevant snippets from your codebase
@url
Reference the markdown converted contents of a given URL
@folder
Uses the same retrieval mechanism as @Codebase, but only on a single folder
@terminal
Reference the last command you ran in your IDE's terminal and its output
@code
Reference specific functions or classes from throughout your project
@file
Reference any file in your current workspace

No Data configured

MCP Servers

Learn more

No MCP Servers configured