20 Security Best Practices for Vibe Coding

20 Security Best Practices for Vibe Coding

securityaicodingbest-practicesvibe-coding

Let's talk about vibe coding - the new way developers are building software using AI assistants. It's like having a coding buddy who can help you write code faster, but there's a catch: this buddy doesn't always think about security first.

Think of it this way: when you use AI to generate code, you're getting a quick solution, but it might not be the safest one. Just like you wouldn't trust a stranger with your house keys, you shouldn't trust AI-generated code without checking it first.

In this guide, we'll look at 20 simple ways to keep your code secure while using AI coding assistants.

1. Don't Trust AI Code Blindly

Imagine you're building a login system, and the AI gives you code that checks passwords. It might work, but it could be storing passwords in plain text - like writing them down on a piece of paper anyone can read. Always check the code the AI gives you, just like you'd proofread an important email.

2. Use Battle-Tested Authentication

When it comes to user login, don't reinvent the wheel. Instead of using AI-generated authentication code, use proven solutions like NextAuth (Indie Kit has got you covered here). It's like using a well-tested recipe instead of making up your own - you know it's going to work safely.

3. Clean Up User Input

Let's say you're building a search feature. The AI might give you code that takes whatever the user types and puts it directly into a database query. That's like letting someone write anything they want on your whiteboard - they could write something that breaks your system.

Here's a safer way:

// Instead of this (unsafe):
app.get('/search', async (req, res) => {
  const query = `SELECT * FROM users WHERE name = '${req.query.name}'`
  const result = await db.query(query)
  res.json(result)
})

// Do this (safe):
app.get('/search', async (req, res) => {
  const name = req.query.name?.trim()
  if (!name || /[^a-zA-Z0-9 ]/.test(name)) {
    return res.status(400).json({ error: 'Invalid input' })
  }
  const result = await db.query('SELECT * FROM users WHERE name = ?', [name])
  res.json(result)
})

And In my opinion, you should use ORMs like Prisma or Drizzle ORM to avoid SQL injection.

4. Keep Secrets Secret

Never put sensitive information like API keys or passwords directly in your code. It's like leaving your house keys under the doormat - anyone can find them. Use environment variables or a secrets manager instead.

5. Frontend Secrets Don't Stay Secret

If you're building a website, remember that anything you put in your frontend code can be seen by anyone. Don't store API keys in your React or Next.js environment files - they'll be visible to users. Instead, create a backend service to handle sensitive operations.

6. Control Who Can Do What

Just because someone can log in doesn't mean they should be able to do everything. Set up clear rules about who can access what. It's like having different keys for different rooms in a building.

7. Always Use HTTPS

Make sure your website uses HTTPS. It's like having a secure phone line instead of shouting your secrets in a crowded room. Set up your server to automatically redirect HTTP to HTTPS.

8. Check Your Dependencies

The AI might suggest using certain libraries, but they might have security holes. Regularly check your project's dependencies for known issues using tools like npm audit or pip-audit.

9. Protect Your API

Your API is like the front door to your application. Make sure it's locked! Add authentication, rate limiting, and proper CORS settings to keep unwanted visitors out.

10. Handle Sessions Safely

When users log in, give them a secure session token. Store it in HTTP-only cookies, not in local storage. It's like giving someone a temporary badge that can't be copied.

11. Be Careful with File Uploads

If your app lets users upload files, be strict about what you accept. It's like having a security guard check what people bring into a building. Only allow specific file types and scan for malware.

12. Give Minimum Access

Follow the principle of least privilege: give users and services only the access they need. It's like giving someone a key to just their office, not the entire building.

13. Watch for Trouble

Set up logging and monitoring to catch security issues early. It's like having security cameras in your building - you can spot problems before they become disasters.

14. Use Modern Security Tools

When the AI suggests using old security methods, choose modern ones instead. For passwords, use bcrypt or Argon2. For encryption, use AES-256-GCM. It's like using a modern lock instead of an old one.

15. Limit Request Rates

Stop attackers from overwhelming your system by limiting how many requests they can make. It's like having a bouncer at a club who only lets in a certain number of people.

const rateLimit = require('upstash/rate-limit')

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per window
  message: 'Too many requests, please try again later',
})

app.use('/login', limiter)

16. Set Up CORS Properly

Control which websites can talk to your API. It's like having a guest list for a party - only let in the people you trust.

const corsOptions = {
  origin: ['https://yourtrusteddomain.com'],
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization'],
}

app.use(cors(corsOptions))

And in NextJS: https://nextjs.org/docs/app/api-reference/config/next-config-js/crossOrigin

17. Secure Your Cloud Setup

If you're using cloud services, make sure they're not accidentally exposed to the internet. It's like making sure all the doors and windows in your house are locked.

18. Test Your Security

Regularly check your application for security holes. Use automated tools and manual testing. It's like having regular health check-ups for your code.

19. Train Your Team

Make sure everyone on your team understands security basics. It's like teaching everyone in your family how to lock the doors properly.

20. Keep Your AI Tools Updated

Use the latest versions of AI coding assistants. They're more likely to suggest secure code. It's like using the latest version of your phone's software to get the newest security features.

Final Thoughts

Vibe coding with AI can make you faster, but security should always come first. Think of it like driving a car - you can go fast, but you need to follow safety rules. Take the time to review and secure your code, and you'll build applications that are both efficient and safe.

Remember: AI is a tool, not a replacement for good security practices. Stay vigilant, keep learning, and always put security first.

Ready to get started?

Join our team of Indie Hackers who are already transforming their workflow with Indie Kit.

+ Discord Community access

199$ discount for the first 200 users