User Agents

Web browsers and everyday web tech, explained

Build Authenticated Loopback Bridge for Browser AI Chats

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

An authenticated local loopback bridge enables secure, private communication between a browser-based AI chat interface and a local AI model or service running on the same machine. This setup routes requests from the browser through a local server that verifies credentials before forwarding them to the AI backend, ensuring only authorized users can access the service. It’s ideal for developers testing local AI agents, maintaining privacy, or integrating browser tools with locally hosted models like Llama.cpp, Ollama, or private GPT servers. The bridge uses localhost (127.0.0.1) to prevent external exposure, while authentication adds a layer of access control.

What You'll Need

  • A local AI server or model runtime (e.g., Ollama, Llama.cpp with REST API, or a custom Flask/FastAPI backend)
  • A modern web browser (Chrome, Firefox, or Edge)
  • Node.js (v18 or higher) installed locally
  • A code editor (VS Code, Sublime Text, or similar)
  • Basic knowledge of command-line operations
  • Optional: SSL certificate for HTTPS (if simulating production-like security)

Step-by-Step

  1. Start your local AI backend: Launch your AI model server. For example, if using Ollama, run ollama serve in a terminal. Ensure it listens on 127.0.0.1:11434 by default. Confirm it’s running by visiting http://localhost:11434 in your browser (you may get a 404, which is normal if no frontend is set up).
  2. Create a project directory: Open a terminal and run mkdir ai-bridge && cd ai-bridge. Initialize a Node.js project with npm init -y.
  3. Install required packages: Run npm install express cors axios jsonwebtoken bcryptjs. Express handles HTTP routing, cors manages browser cross-origin settings, axios forwards requests, and jwt/bcryptjs handle authentication.
  4. Create the bridge server file: In the project folder, create server.js. Open it in your editor and begin writing the Express app.
  5. Set up Express and middleware: Add the following to server.js:
    const express = require('express');
    const cors = require('cors');
    const axios = require('axios');
    const jwt = require('jsonwebtoken');
    const bcrypt = require('bcryptjs');
    
    const app = express();
    app.use(cors());
    app.use(express.json());
    
    const PORT = 3001;
    const AI_URL = 'http://localhost:11434'; // Ollama default
    const SECRET = 'your-super-secret-jwt-key'; // Change this in production
    
    // In-memory user store (replace with DB in production)
    const users = [
      {
        username: 'user1',
        password: bcrypt.hashSync('password123', 10)
      }
    ];
    
  6. Add authentication endpoints: Below the user store, add login and token verification:
    app.post('/login', (req, res) => {
      const { username, password } = req.body;
      const user = users.find(u => u.username === username);
      if (user && bcrypt.compareSync(password, user.password)) {
        const token = jwt.sign({ username }, SECRET, { expiresIn: '1h' });
        res.json({ token });
      } else {
        res.status(401).json({ error: 'Invalid credentials' });
      }
    });
    
  7. Create authenticated proxy route: Add a route that verifies the JWT before forwarding requests:
    function authenticateToken(req, res, next) {
      const authHeader = req.headers['authorization'];
      const token = authHeader && authHeader.split(' ')[1];
      if (!token) return res.sendStatus(401);
    
      jwt.verify(token, SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user;
        next();
      });
    }
    
    app.post('/api/chat', authenticateToken, async (req, res) => {
      try {
        const response = await axios.post(`${AI_URL}/api/generate`, req.body);
        res.json(response.data);
      } catch (error) {
        res.status(500).json({ error: 'AI backend error' });
      }
    });
    
  8. Start the server: Add app.listen(PORT, () => console.log(`Bridge running on http://localhost:${PORT}`)); at the end of server.js. Save the file.
  9. Run the bridge: In the terminal, run node server.js. You should see the message that the server is running on port 3001.
  10. Test from browser: Create a simple HTML page with a form that sends a POST request to http://localhost:3001/login with username and password. On success, store the returned JWT and use it in subsequent requests to http://localhost:3001/api/chat with header Authorization: Bearer <token>.

Common Mistakes

  • Using weak or default JWT secrets: Always change the SECRET value to a long, random string.
  • Forgetting to start the AI backend first: The bridge fails silently if the target service isn’t running.
  • Not handling CORS properly: Even on localhost, browsers enforce CORS. The cors() middleware is essential.
  • Hardcoding credentials in production: The in-memory user list is for testing only. Use a database or secure credential store in real deployments.
  • Exposing the bridge to public networks: Ensure the server binds only to 127.0.0.1, not 0.0.0.0, to prevent external access.

Tips

  • Use environment variables for secrets: Replace hardcoded SECRET with process.env.JWT_SECRET and load via .env file.
  • Add logging: Use console.log or a logging library to track requests and errors during development.
  • Test authentication separately: Use tools like curl or Postman to verify login and chat endpoints before browser integration.
  • Rate limiting: Add express-rate-limit to prevent brute-force attacks on the login endpoint.
  • Validate request bodies: Ensure incoming chat payloads match expected schema before forwarding.

Troubleshooting

If the bridge doesn’t respond, first check that both the Node.js server and AI backend are running. Use curl http://localhost:11434 to verify the AI service. If login fails, confirm password hashing is correct and credentials match. For CORS errors, ensure the cors() middleware is applied. If JWT verification fails, double-check the token format and secret key. If the proxy returns 500 errors, inspect the AI backend logs for malformed requests. Always verify request URLs and HTTP methods match what the AI backend expects. Use browser developer tools to inspect network requests and headers.

Frequently Asked Questions

Can this bridge work with any local AI model?

Yes, as long as the model exposes a REST API. Adjust the AI_URL and request format in the proxy route to match the model’s endpoint.

Is HTTPS required for local use?

Not strictly, but it’s recommended if simulating production. Use tools like mkcert to generate local HTTPS certificates.

How do I add more users?

Modify the users array to include additional username/password objects. Hash passwords using bcrypt.hashSync().

Can I host this bridge on a different port?

Yes, change the PORT constant in server.js. Ensure your browser client uses the updated port.

What if my AI backend uses WebSockets?

This setup uses HTTP. For WebSockets, replace axios with a WebSocket proxy using ws or socket.io.