Beginner Tech Blog

Vercel でプレビュー環境をメンバー以外に提供したい(簡易版)

2026/03/12

Vercel でプレビュー環境をメンバー以外に提供したい...
取り急ぎの簡易な手段としては

  1. Vercel側の設定を変更
    Project > Settings > Deployment Protection > Vercel Authentication を OFF

  2. Middleware で BASIC認証の導入
    サンプルコード。productionのみBASIC認証が入らないようにする。

// 本番環境ではBasic認証をスキップ。プレビューのみBasic認証をかける。
  // Vercelでは本番もプレビューもNODE_ENV=productionのため、VERCEL_ENVで判定する
  const isProduction =
    process.env.VERCEL_ENV === 'production' ||
    (process.env.VERCEL_ENV == null && process.env.NODE_ENV === 'production');

  if (!isProduction) {
    const validUser = process.env.BASIC_AUTH_USER;
    const validPassword = process.env.BASIC_AUTH_PASSWORD;
    // 環境変数が設定されている場合のみBasic認証を実施
    if (validUser && validPassword) {
      const basicAuth = request.headers.get('authorization');

      if (basicAuth) {
        const authValue = basicAuth.split(' ')[1];
        if (authValue) {
          const decoded = atob(authValue);
          const colonIndex = decoded.indexOf(':');
          const user = colonIndex >= 0 ? decoded.slice(0, colonIndex) : decoded;
          const pwd = colonIndex >= 0 ? decoded.slice(colonIndex + 1) : '';

          if (user !== validUser || pwd !== validPassword) {
            return new NextResponse('Authentication required', {
              status: 401,
              headers: {
                'WWW-Authenticate': 'Basic realm="Secure Area"',
              },
            });
          }
        } else {
          return new NextResponse('Authentication required', {
            status: 401,
            headers: {
              'WWW-Authenticate': 'Basic realm="Secure Area"',
            },
          });
        }
      } else {
        return new NextResponse('Authentication required', {
          status: 401,
          headers: {
            'WWW-Authenticate': 'Basic realm="Secure Area"',
          },
        });
      }
    }
  }
© 2026 Beginner Tech Blog | Built with U