Next.js Discord

Discord Forum

Why does cookies not overwrite

Unanswered
Doberman Pinscher posted this in #help-forum
Open in Discord
Doberman PinscherOP
i have a middleware that request this route handler and many other functions that check fetches this route before another fetch. It does work when i don't have an access token, it creates it and it is valid, but if it already exists it doesn't overwrite it.
export async function GET() {
    const refreshTokenCookie = cookies().get('refresh_token')?.value

    if (!refreshTokenCookie) {
        return NextResponse.json(
            { message: 'Вы не авторизованы' || 'you are not authenticated' },
            { status: 500 }
        )
    }

    try {
        const isAuth = await fetch(`${BASE_URL}/account/refresh/`, {
            method: 'POST',
            body: JSON.stringify({ refresh: refreshTokenCookie }),
            headers: {
                'Content-Type': 'application/json',
            },
        })
        const response = NextResponse.next()

        const data = await isAuth.json()
        const newAccessToken = data.access

        response.cookies.delete('access_token')

        response.cookies.set({ name: 'access_token', value: newAccessToken })

        return NextResponse.json({ message: 'token refreshed' })
    } catch (error) {
        console.log(error)
    }
}

3 Replies

first update Next because there had been bugs around cookies for a while
then if you set the cookie you probably don't need to delete it first?
you need to check what are the headers of the final response