#TypeError: Cannot read properties of undefined (reading 'delete')

1 messages · Page 1 of 1 (latest)

proven lava
#

TypeError: Cannot read properties of undefined (reading 'delete')

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export default function middleware(
request: NextRequest,
response: NextResponse
) {
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-next-pathname", request.nextUrl.pathname);

const currentUser = request.cookies.get("user");
const authRoutes = ["/login", "/sign-up", "/verify-email"];

if (!currentUser && !authRoutes.includes(request.nextUrl.pathname)) {
response.cookies.delete("accessToken");
response.cookies.delete("refreshToken");
response.cookies.delete("user");
const url = request.nextUrl.clone();
url.pathname = "/login";

return NextResponse.redirect(url, {
  headers: requestHeaders,
});

}

if (currentUser && authRoutes.includes(request.nextUrl.pathname)) {
const url = request.nextUrl.clone();
url.pathname = "/";

return NextResponse.redirect(url, {
  headers: requestHeaders,
});

}

const refreshToken = request.cookies.get("refreshToken")?.value;
const parsedRefreshToken = JSON.parse(refreshToken || "{}");

if (
currentUser &&
refreshToken &&
new Date(parsedRefreshToken.expiresIn) < new Date()
) {
response.cookies.delete("accessToken");
response.cookies.delete("refreshToken");
response.cookies.delete("user");
const url = request.nextUrl.clone();
url.pathname = "/login";

return NextResponse.redirect(url, {
  headers: requestHeaders,
});

}

return NextResponse.next({
request: {
headers: requestHeaders,
},
});
}

export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.\.png).)"],
};

weak totemBOT
#

Hi @proven lava. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the provided code, it seems like you're trying to delete cookies from the response object in your Next.js middleware. However, you're encountering a TypeError: Cannot read properties of undefined (reading 'delete') error.

This error typically occurs when you're trying to access a property or method on an undefined object. In this case, it seems like response.cookies might be undefined.

Unfortunately, the knowledge sources provided do not contain any information about handling cookies in Next.js middleware or about the specific error you're encountering. Therefore, I can't provide a confident solution to your problem based on the provided knowledge sources.

However, I would recommend checking the official Next.js documentation or other reliable sources to understand how to correctly handle cookies in Next.js middleware.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@proven lava kapa.ai is still learning and improving, please let us know how it did by reacting below

proven lava
#

@weak totem

Can I run fetch function in middleware/

weak totemBOT
#

Let me check the knowledge base for you. One moment! :books:

#

According to the Vercel documentation (https://vercel.com/docs/workflow-collaboration/conformance/rules/NO_FETCH_FROM_MIDDLEWARE), making a fetch call from Next.js middleware or its transitive dependencies is generally discouraged. This is because the middleware runs at the Edge, meaning the code is globally distributed. If a fetch call is made to a backend that is not globally distributed, the latency of the middleware function could be significantly high.

However, if you still need to make a fetch call from middleware, it will be flagged and reviewed to ensure it's an appropriate use case. Here's an example from the same documentation:

// experiments.ts
export async function getExperiments() {
 const res = await fetch('/experiments');
 return res.json();
}

// middleware.ts
export async function middleware(
 request: NextRequest,
 event: NextFetchEvent,
): Promise<Response> {
 const experiments = await getExperiments();
 
 if (experiments.includes('new-marketing-page')) {
 return NextResponse.rewrite(MARKETING_PAGE_URL);
 }
 return NextResponse.next();
}

In this example, the getExperiments function in experiments.ts makes a fetch call, and this function is used in middleware.ts.

Please note that this is just an example and the actual implementation may vary based on your specific use case and requirements.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@proven lava kapa.ai is still learning and improving, please let us know how it did by reacting below

proven lava
#

@weak totem

it only sets the last cookie, if I replace order of setting it doesn't matter
const data = await res.json();
const response = NextResponse.next();

    console.log(data.user, accessToken, refreshToken);
    // set(...args: [key: string, value: string, cookie?: Partial<ResponseCookie>] | [options: ResponseCookie]): this;
    response.cookies.set("user", JSON.stringify(data.user));
    response.cookies.set("refreshToken", JSON.stringify(refreshToken));
    response.cookies.set("accessToken", JSON.stringify(accessToken));

    return response;
weak totemBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The issue you're facing might be due to the way cookies are being set in the response. In Next.js, the cookies.set method is used to set cookies in the response. However, if multiple cookies are set in the same response, they should all be included in the Set-Cookie header of the response.

Here's an example of how to set multiple cookies in a response:

const response = NextResponse.next();
response.cookies.set('user', JSON.stringify(data.user));
response.cookies.set('refreshToken', JSON.stringify(refreshToken));
response.cookies.set('accessToken', JSON.stringify(accessToken));
return response;

In this example, three cookies (user, refreshToken, and accessToken) are being set in the response. Each call to response.cookies.set should add a new Set-Cookie header to the response.

If only the last cookie is being set, it might be due to an issue with the way the cookies are being read or parsed on the client side. It's also possible that there's an issue with the way the Set-Cookie headers are being handled by the browser or the server.

Unfortunately, the provided knowledge sources do not contain any information about handling multiple cookies in Next.js or about the specific issue you're encountering. Therefore, I can't provide a confident solution to your problem based on the provided knowledge sources.

However, I would recommend checking the official Next.js documentation or other reliable sources to understand how to correctly handle multiple cookies in Next.js.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: