Skip to content

Instantly share code, notes, and snippets.

@f1729
Forked from mtt87/_middleware.ts
Created November 9, 2022 20:36
Show Gist options
  • Select an option

  • Save f1729/1c7de17ae8b1103a88aa9b6c086c2519 to your computer and use it in GitHub Desktop.

Select an option

Save f1729/1c7de17ae8b1103a88aa9b6c086c2519 to your computer and use it in GitHub Desktop.

Revisions

  1. @mtt87 mtt87 created this gist Dec 21, 2021.
    42 changes: 42 additions & 0 deletions _middleware.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    import { addYears } from 'date-fns'
    import { NextRequest, NextResponse } from 'next/server'

    function middleware(req: NextRequest) {
    if (req.nextUrl.pathname.startsWith('/api')) {
    return NextResponse.next()
    }

    if (process.env.VERCEL_ENV !== 'preview') {
    return NextResponse.next()
    }

    if (req.cookies['let-me-in'] === process.env.BASIC_AUTH_PASSWORD) {
    return NextResponse.next()
    }

    const basicAuth = req.headers.get('authorization')

    if (basicAuth) {
    const auth = basicAuth.split(' ')[1]
    const [user, pwd] = Buffer.from(auth, 'base64').toString().split(':')

    if (user === 'username' && pwd === process.env.BASIC_AUTH_PASSWORD) {
    const response = NextResponse.next()
    const expire = addYears(new Date(), 1).toUTCString()
    response.headers.set(
    'Set-Cookie',
    `let-me-in=${process.env.BASIC_AUTH_PASSWORD}; Domain=.example.com; Secure; HttpOnly; Expires='${expire}'`,
    )
    return response
    }
    }

    return new Response('Auth required', {
    status: 401,
    headers: {
    'WWW-Authenticate': 'Basic realm="Secure Area"',
    },
    })
    }

    export default middleware