vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.14k stars 27.02k forks source link

Serving static file in /public dir failed when having redirect logic on next middleware #35722

Closed bryanltobing closed 2 years ago

bryanltobing commented 2 years ago

Verify canary release

Provide environment information

Operating System: Platform: win32 Arch: x64 Version: Windows 1! Home Single Language Binaries: Node: 16.13.2 npm: N/A Yarn: N/A pnpm: N/A Relevant packages: next: 12.1.2 & 12.1.3-canary.0 react: 17.0.2 react-dom: 17.0.2

What browser are you using? (if relevant)

Microsoft Edge

How are you deploying your application? (if relevant)

next start

Describe the Bug

if (!session && !UNPROTECTED_PAGE_NAMES.includes(pageName)) {
    url.pathname = `/login`;

    return redirect(url);
  }

I am having this logic on my next.js middleware to check for authentication

When I have this logic active on my middleware. the app always failed to serve static image

and I got this warning the requested resource isn't a valid image for /static/images/example.png received text/html; charset=utf-8

Expected Behavior

The app still able to serve static files, in this case, is image

To Reproduce

I have this kind of authentication checker

const middleware: NextMiddleware = async req => {
   const session = req.cookies.session
   const { redirect, next } = NextResponse

   const UNPROTECTED_PAGE_NAMES = [
    "/login",
    "/register",
  ];

  // every time this logic active. app will failed to server static files
  if (!session && !UNPROTECTED_PAGE_NAMES.includes(pageName)) {
    url.pathname = `/login`;

    return redirect(url);
  }

  return next()
}

for instance in my /about routes

import Image from 'next/image'

const About = () => {
   return <Image src="/static/images/example.png" width={100} height={100} alt="example"/>
}

I will get this warning in the console

the requested resource isn't a valid image for /static/images/example.png received text/html; charset=utf-8

also sometimes another error like this ImageError: The requested resource isn't a valid image. at imageOptimizer (C:\project\node_modules\next\dist\server\image-optimizer.js:271:19) at runMicrotasks (<anonymous>) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async C:\project\node_modules\next\dist\server\next-server.js:179:72 at async C:\project\node_modules\next\dist\server\response-cache.js:72:36 { statusCode: 400 }

balazsorban44 commented 2 years ago

It looks like you are not handling the case when Middleware is run for public files. You probably do not want to invoke a redirection for static files.