How Prompt-Optimizer Implements Authentication and Access Control

Prompt-Optimizer protects its web interface using a simple password-based authentication flow enforced by an API endpoint and edge middleware, storing credentials in environment variables and session state in HttpOnly cookies.

The open-source prompt-optimizer repository by linshenkx provides a lightweight yet effective approach to authentication and access control suitable for serverless deployments. The system relies on two core files—api/auth.js and middleware.js—to validate credentials and guard routes without requiring complex user management databases.

Core Components of the Authentication System

API Endpoint: api/auth.js

Located at api/auth.js, this serverless function handles password verification, cookie issuance, and logout operations. It reads the secret password from the ACCESS_PASSWORD environment variable and compares it against user submissions via POST requests.

Edge Middleware: middleware.js

The middleware.js file runs at the edge runtime to intercept every incoming request before it reaches the application. It checks for the presence of a valid vercel_access_token cookie and either allows the request to proceed or returns an HTML authentication page.

Authentication Flow and Access Control

The authentication and access control mechanism follows a straightforward stateless flow:

  1. Initial Request: When a user accesses any protected route, the middleware intercepts the request.
  2. Cookie Validation: The middleware checks for the vercel_access_token cookie and validates it against the ACCESS_PASSWORD environment variable.
  3. Login Prompt: If the cookie is missing or invalid, the middleware returns an HTML login page generated by the generateAuthPage function.
  4. Credential Verification: The user submits their password via a POST request to /api/auth with the action parameter set to "verify".
  5. Session Creation: Upon successful validation, api/auth.js sets an HttpOnly, SameSite-Strict cookie named vercel_access_token with a 7-day expiration.
  6. Protected Access: Subsequent requests automatically include the cookie, allowing the middleware to pass them through to the application.
  7. Logout: Users can terminate their session by calling /api/auth?action=logout, which clears the authentication cookie.

Environment Configuration and Security Settings

The system uses environment-driven configuration to keep credentials out of the source code. Developers must define the ACCESS_PASSWORD variable in their .env.local file or deployment platform.

When ACCESS_PASSWORD is undefined, the middleware disables authentication entirely, making the site publicly accessible. This behavior supports public demos and development environments without code changes.

The vercel_access_token cookie implements several security best practices:

  • HttpOnly: Prevents JavaScript access to the token
  • SameSite=Strict: Protects against CSRF attacks
  • Secure flag: Enabled automatically in production environments (NODE_ENV === 'production')
  • Max-Age: Set to 604800 seconds (7 days)

Implementation Code Examples

The following examples demonstrate the actual implementation found in the prompt-optimizer repository.

// File: api/auth.js
export default function handler(req, res) {
  const accessPassword = process.env.ACCESS_PASSWORD;

  // No password configured → open access
  if (!accessPassword) {
    return res.status(200).json({ success: true, message: 'No password protection' });
  }

  if (req.method === 'POST') {
    const { password, action } = req.body;
    if (action === 'verify') {
      if (password === accessPassword) {
        const maxAge = 60 * 60 * 24 * 7; // 7 days
        res.setHeader('Set-Cookie', [
          `vercel_access_token=${accessPassword}; HttpOnly; Path=/; Max-Age=${maxAge}; SameSite=Strict${process.env.NODE_ENV === 'production' ? '; Secure' : ''}`
        ]);
        return res.status(200).json({ success: true, message: 'Authentication successful' });
      }
      return res.status(401).json({ success: false, message: 'Invalid password' });
    }
  }
  // …other branches omitted for brevity
}

Edge Middleware Request Guarding

// File: middleware.js
export default function middleware(request) {
  const accessPassword = process.env.ACCESS_PASSWORD;
  if (!accessPassword) return;               // No auth needed

  const cookieHeader = request.headers.get('cookie');
  let authenticated = false;
  if (cookieHeader) {
    const token = cookieHeader
      .split(';')
      .find(c => c.trim().startsWith('vercel_access_token='));
    if (token) authenticated = token.split('=')[1] === accessPassword;
  }

  if (authenticated) return;                // Allow request to continue
  // Render login page when not authenticated
  return new Response(generateAuthPage(preferChinese), {
    status: 200,
    headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache, no-store, must-revalidate' },
  });
}

Client-Side Logout Implementation

// Triggered by the client (e.g., a "Log out" button)
fetch('/api/auth?action=logout')
  .then(() => window.location.reload());

Summary

  • Prompt-Optimizer implements authentication and access control through a lightweight password-based system using api/auth.js and middleware.js.
  • The ACCESS_PASSWORD environment variable drives the entire security model; when undefined, the application operates in open-access mode.
  • Authentication state persists via a vercel_access_token cookie with HttpOnly, SameSite-Strict, and optional Secure flags for 7 days.
  • Edge middleware intercepts all requests to validate cookies before serving content, falling back to an HTML login page for unauthenticated users.

Frequently Asked Questions

How do I enable password protection for my Prompt-Optimizer deployment?

Set the ACCESS_PASSWORD environment variable in your hosting platform (e.g., Vercel, Netlify) or in a .env.local file during local development. Once defined, the middleware automatically enforces authentication on all routes.

What happens if I don't set an ACCESS_PASSWORD environment variable?

When ACCESS_PASSWORD is undefined, both middleware.js and api/auth.js bypass authentication checks entirely. The application behaves as a publicly accessible tool without any login requirements, which is useful for demonstrations or open deployments.

Yes. The vercel_access_token cookie uses the HttpOnly flag to prevent JavaScript access (mitigating XSS) and the SameSite=Strict flag to prevent cross-site request forgery. In production environments, the Secure flag is also appended to ensure transmission only over HTTPS.

How long does the authentication session last?

The cookie expires after 7 days (604,800 seconds) by default. Users must re-enter the password after this period, or they can manually terminate their session earlier by triggering the logout action, which clears the cookie immediately.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →