Next.js Discord

Discord Forum

Set custom headers for url with asset

Unanswered
English Spot posted this in #help-forum
Open in Discord
English SpotOP
Hey i have a protected url lets say for example https://example.com/test.jpg
and it has to have custom header for authorization how in next js can i set custom header for url with assets

5 Replies

@English Spot Hey i have a protected url lets say for example https://example.com/test.jpg and it has to have custom header for authorization how in next js can i set custom header for url with assets
Northeast Congo Lion
idk if possible but could try next middleware, listen for requests to routes and check header
next assets are stored under /_next/....
English SpotOP
For more explanation i created Cloudflare worker that serve files from R2 when request have custom authorization header
Northeast Congo Lion
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  
  //check headers in req.headers and check for token
  if (header found && token valid) {
    return NextResponse.next();
  }
  return NextResponse.redirect(new URL('/', request.url));
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: '/((?!_next\/static|_next\/image).*)',
}
something like this