DEV Community

Cover image for Security Basics in the Age of AI-Assisted Coding
Alex Hyett
Alex Hyett

Posted on • Originally published at alexhyett.com on

Security Basics in the Age of AI-Assisted Coding

I have been using AI a lot more recently even to help with code at work. I don't yet trust it enough to make changes on existing codebases but for new scripts I have definitely seen a productivity increase from using it.

One thing I have noticed with using AI on languages I am familiar with, is that it is easier to spot when it is doing something dodgy.

While AI can help us write code faster, it might not always understand the security implications of what it's generating. If you are generating prototypes than this isn't much of a concern but for anything else you need to at least understand the basics. Here's a rundown of essential security considerations that every developer should keep in mind, especially when “vibe coding” with AI.

1. Keep Your Secrets Secret #

One of the most basic yet critical security practices is properly handling sensitive information.

I've heard countless stories where developers accidentally committed their .env files containing API keys, database credentials, and other secrets.

Instead:

  • Create a .env.example file with dummy values
  • Add .env to your .gitignore
  • Document the required environment variables
  • Use secret management services in production
# .env.example 
DATABASE_URL=postgresql://user:password@localhost:5432/mydb API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

If you are working on a personal project and want to store credentials in a .env file then you should at least encrypt it (see Encrypting secrets in git)

2. Keep API Calls Server-Side #

When AI generates code for API integrations, it might suggest making calls directly from the client. This is a massive security risk! Your API keys should never be exposed in client-side code.

❌ Bad (client-side):

const response = await openai.createCompletion({ 
    apiKey: 'sk-your-actual-key-here', // NEVER DO THIS 
    model: "text-davinci-003", 
    prompt: userInput 
});
Enter fullscreen mode Exit fullscreen mode

✅ Good (server-side):

// Client
const response = await fetch('/api/generate-text', 
    { method: 'POST', body: JSON.stringify({ prompt: userInput }) 
}); 

// Server 
app.post('/api/generate-text', async (req, res) => { 
    const response = await openai.createCompletion({ 
        apiKey: process.env.OPENAI_API_KEY, 
        model: "text-davinci-003", 
        prompt: req.body.prompt 
    }); 
    res.json(response.data); 
});
Enter fullscreen mode Exit fullscreen mode

3. Authentication vs. Authorization #

This is a classic confusion that even established companies get wrong. Remember the Moonpig incident where a simple API endpoint allowed access to any user's data without proper authorization?

  • Authentication : Verifying who someone is
  • Authorization : Determining what they're allowed to do

Just because a user is logged in (authenticated) doesn't mean they should have access to everything (authorized).

❌ Bad:

app.get('/api/user/:id/data', (req, res) => {
  // Only checking if user is logged in
  if (req.user) {
    return getUserData(req.params.id);
  }
});
Enter fullscreen mode Exit fullscreen mode

✅ Good:

app.get('/api/user/:id/data', (req, res) => {
  // Check if logged in AND authorized
  if (req.user && (req.user.id === req.params.id || req.user.isAdmin)) {
    return getUserData(req.params.id);
  }
});
Enter fullscreen mode Exit fullscreen mode

4. SQL Injection #

AI might generate quick database queries, but be careful about string concatenation. Always use parameterized queries.

❌ Bad:

const query = `SELECT * FROM users WHERE username = '${userInput}'`;
Enter fullscreen mode Exit fullscreen mode

✅ Good:

const query = 'SELECT * FROM users WHERE username = $1'; 
const result = await pool.query(query, [userInput]);
Enter fullscreen mode Exit fullscreen mode

5. Cross-Site Scripting (XSS) #

XSS attacks occur when malicious scripts are injected into trusted websites. Always sanitize user input and use proper encoding when displaying data.

❌ Bad:

document.innerHTML = userInput;
Enter fullscreen mode Exit fullscreen mode

✅ Good:

document.textContent = userInput;
// Or use a sanitization library
document.innerHTML = DOMPurify.sanitize(userInput);
Enter fullscreen mode Exit fullscreen mode

6. Data Transfer Objects (DTOs) #

When AI generates API endpoints, it might expose your entire database models. Always use DTOs to control what data gets sent to and from your API.

❌ Bad:

app.put('/api/user/:id', async (req, res) => {
  const user = await User.update(req.params.id, req.body);
  // Oops, user could update isAdmin=true!
});
Enter fullscreen mode Exit fullscreen mode

✅ Good:

app.put('/api/user/:id', async (req, res) => {
  const allowedFields = ['name', 'email', 'avatar'];
  const updateData = pick(req.body, allowedFields);
  const user = await User.update(req.params.id, updateData);
});
Enter fullscreen mode Exit fullscreen mode

Other things to look out for #

I have only scratched the surface of some main security issues you might come across if you trust AI to code everything for you. Other things to consider are:

  1. Input Validation : Always validate and sanitize input data, never trust what a user sends you. (e.g. "username": "; DROP TABLE users;")
  2. CORS Configuration : Don't just copy-paste CORS settings. Understand and restrict allowed origins.
  3. Dependencies : Given many AI models aren't trained on recent data they may recommend outdated packages. Always check for security advisories and keep dependencies updated.
  4. Rate Limiting : Protect your APIs from abuse by implementing rate limiting.
  5. Error Handling : Don't expose detailed error messages to clients that might reveal system information.

❤️ Picks of the Week #

📚 BookThe Little Book About OS Development — I am not sure if I have the time or patience to build my own operating system but if you did this book is for you!

📚 BookArchitecture Patterns with Python — An excellent resource for learning domain-driven design and enterprise patterns in Python, with practical examples.

📝 ArticleConverting an image into a black and white SVG — This is cool, I will have to try this out with some of my drawings.

🛠️ ToolSearch My Site — An open-source search engine specifically designed for personal and independent websites.

🤖 AI4o Image Generation —Image generation is getting scarily good. The images in front of the whiteboard in particular would have fooled me.

📝 ArticleThe Highest-ranking Personal Blogs of Hacker News — This is a good list, I definitely need to add some of these to my RSS reader. I am glad to see Julia Evans so high on the list, her stuff is awesome.

📝 ArticleThe Role of Developer Skills in Agentic Coding — Martin has done a few posts recently about AI. Even though I often need to correct what the AI has generated it is certainly made me more productive.

📝 ArticleHow to Use Em Dashes, En Dashes, and Hyphens — I keep getting corrected to use an em dash in places by my grammar tool. I am not even sure where an em dash is on the keyboard.

🛠️ ToolMost Promoted and Blocked Domains on Kagi — You can tell by the promoted domains that Kagi is mostly used by developers. I have since moved to Searxng, but I should see if I can customise it and block some domains on this list.

📝 ArticleUsing uv and PEP 723 for Self-Contained Python Scripts — I have started using uv this week and it is good. It is cool that it is so easy to have a self-contained app with python.

🎮 GameClaim for a Missing Tooth — This is genius. My kids still believe in the tooth fairy. Part of me wants to self-host this set up DNS for dot.gov.uk.

🤖 AIWe Hacked Gemini's Python Sandbox — These always fascinate me. I should really look into doing some bug bounties to earn some extra money!

📰 NewsxAI has Acquired X, xAI Now Valued at $80B — I am thinking of buy a 0.00001% share of my own company for £10 making it worth £100 million 🤣.

📝 ArticleIn the 1980s We Downloaded Games from the Radio — I used to play on my Dad's ZX Spectrum as a kid. I never knew that this was a thing.

🛠️ ToolCaptrice - Guitar Practice App — As a guitarist I need to give this a go!

💻 DevMinimal CSS-only Blurry Image Placeholders — This is a great use of CSS.

📺 TVTV Garden — I never knew there were so many IPTV channels available. I stopped watching live TV a while ago, but this is quite interesting.

🤖 AIGemini 2.5 Pro vs. Claude 3.7 Sonnet: Coding Comparison — It looks like Gemini 2.5 Pro is the new champion when it comes to code generation.

💻 DevNue - Apps Lighter than a React Button — I think this is a bit misleading as React without all the other libraries isn't that big but any attempt to make apps lighter is progress.

🎨 ArtAnimals Made from 13 Circles — This is really cool!

📰 NewsUS Administration Announces 34% Tariffs on China, 20% on EU — There is “only” a 10% tariff on UK imports, but it is still going to have an impact. I wonder how much damage Trump can cause in the short amount of time he is in power.

🛠️ ToolHeadscale — I use Tailscale all the time for my home network. A lot of Tailscale is already open source but it is good to see that people are trying to make the rest open source as well.

🛠️ ToolOpenNutrition — This is great. I always wondered where companies get nutrition data from, but I suspect it is from paid datasets.

💻 DevAnimeJs v4 Is Here — It is impressive what can be done in the browser now when it comes to image generation.

🤖 AIAn Image of an Archeologist Adventurer — I am not sure OpenAI will be able to claim their new image generation tool wasn't trained on copyright data.


💬 Quote of the Week #

Yesterday I was clever, so I wanted to change the world. Today I am wise so I am changing myself. — Rumi

From the book Nothing You Don't Already Know by Alexander den Heijer.

Top comments (0)