How to send cookie to next js middleware(static page)?

21 Views Asked by At

I have a static authorization page. After successful authorization I update the cookie and redirect to /profile.

const handleConfirmSuccess = (data: string) => {
    AuthService.otp({ authIdentifier, otpCode: data })
        .then((resp) => {
            setCookie('accessToken', resp.data.accessToken);
            setCookie('refreshToken', resp.data.refreshToken);
            setIsCorrect(true);
            router.push('/profile');
        })
        .catch((error) => {
            if (error instanceof BadRequestError) {
                showErrorHandler(error.title);
                setIsError(true);
            }
            setResetOTP(!resetOTP);
        });
};

After middleware does not see the token and redirects back to /auth.

export default function middleware(request: NextRequest) {
    const accessToken = request.cookies.get('accessToken')?.value;
    console.log('\naccessToken\n', accessToken?.slice(0, 10));
    console.log('cookies\n', request.cookies);
    if (request.nextUrl.pathname === '/secret-event') {
        if (!accessToken) {
            const eventId = request.nextUrl.searchParams.get('event-id');
            const redirectURL = new URL(`/auth?backURL=event/${eventId}`, request.url);
            return NextResponse.redirect(redirectURL);
        }
    }

    if (request.nextUrl.pathname === '/profile') {
        if (!accessToken) {
            return NextResponse.redirect(new URL(`/auth`, request.url));
        }
    }

    return NextResponse.next();
}

How to pass cookies correctly?

0

There are 0 best solutions below