QuiiBz / next-international

Type-safe internationalization (i18n) for Next.js
https://next-international.vercel.app
MIT License
1.19k stars 52 forks source link

Next Response Type error #320

Closed CarlosZiegler closed 6 months ago

CarlosZiegler commented 6 months ago

Describe the bug If need to use middleware with Auth we get some incompatible Types error: Property 'redirect' does not exist on type 'NextResponse<unknown>'. Did you mean to access the static member 'NextResponse<unknown>.redirect' instead?ts(2576)

To Reproduce Add a HOC withAuth from next-auth and try to use redirect duntion :

import { getToken } from 'next-auth/jwt';
import { withAuth } from 'next-auth/middleware';
import { NextMiddlewareResult } from 'next/dist/server/web/types';
import { redirect } from 'next/navigation';
import { NextResponse as Response, type NextRequest, type NextResponse } from 'next/server';

import { I18nMiddleware } from './lib/locales/locale-middleware';

const allowedRoutes = ['/sign-', '/de/sign-', '/en/sign-'];

export default withAuth(
  async function middleware(request: NextRequest) {
    const nextResponse = I18nMiddleware(request);

    const token = await getToken({ req: request });

    if (!token) {
      if (allowedRoutes.some((route) => request.nextUrl.pathname.startsWith(route))) {
        return nextResponse;
      }

      let callback = request.nextUrl.pathname;
      if (request.nextUrl.search) {
        callback += request.nextUrl.search;
      }

     // Here qe get the error. 
      return nextResponse.redirect(new URL(`/sign-in?callbackUrl=${encodeURIComponent(callback)}`, request.url));
    }

    return nextResponse;
  },
  {
    callbacks: {
      async authorized() {
        // This is a work-around for handling redirect on auth pages.
        // We return true here so that the middleware function above
        // is always called.
        return true;
      },
    },
  },
);

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)'],
};

Expected behavior We expected that types are compatible from NextResponse.

Screenshots

image

About (please complete the following information):

QuiiBz commented 6 months ago

redirect is a static method of the NextResponse class. Given your code, you should use Response.redirect instead of nextResponse.redirect.