Build Authenticated Loopback Bridge for Browser AI Chats
In this article
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
- Start your local AI backend: Launch your AI model server. For example, if using Ollama, run
ollama servein a terminal. Ensure it listens on127.0.0.1:11434by default. Confirm it’s running by visitinghttp://localhost:11434in your browser (you may get a 404, which is normal if no frontend is set up). - Create a project directory: Open a terminal and run
mkdir ai-bridge && cd ai-bridge. Initialize a Node.js project withnpm init -y. - 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. - Create the bridge server file: In the project folder, create
server.js. Open it in your editor and begin writing the Express app. - 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) } ]; - 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' }); } }); - 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' }); } }); - Start the server: Add
app.listen(PORT, () => console.log(`Bridge running on http://localhost:${PORT}`));at the end ofserver.js. Save the file. - Run the bridge: In the terminal, run
node server.js. You should see the message that the server is running on port 3001. - Test from browser: Create a simple HTML page with a form that sends a POST request to
http://localhost:3001/loginwith username and password. On success, store the returned JWT and use it in subsequent requests tohttp://localhost:3001/api/chatwith headerAuthorization: Bearer <token>.
Common Mistakes
- Using weak or default JWT secrets: Always change the
SECRETvalue 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, not0.0.0.0, to prevent external access.
Tips
- Use environment variables for secrets: Replace hardcoded
SECRETwithprocess.env.JWT_SECRETand load via.envfile. - Add logging: Use
console.logor 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-limitto 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 theAI_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 theusers array to include additional username/password objects. Hash passwords using bcrypt.hashSync().
Can I host this bridge on a different port?
Yes, change thePORT 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 usingws or socket.io.