session.destroy not working in middleware
dsbrianwebster opened this issue · comments
session.destroy()
works as expected outside of middleware. But when invoking it from middleware via iron-session/edge
, it appears to have no effect.
NextJS "13.2.4"
Iron Session: "^6.3.1"
// middleware.ts
import { NextResponse } from 'next/server';
import { getIronSession } from 'iron-session/edge';
import type { NextRequest } from 'next/server';
import { sessionOptions } from '~/server/session';
export const config = {
matcher: ['/account/:path*'],
};
export const middleware = async (req: NextRequest) => {
const res = NextResponse.next();
const session = await getIronSession(req, res, sessionOptions);
session.destroy(); // ! This is not destroying the session / removing the cookie
return NextResponse.redirect(new URL('/', req.url));
};
Why are you destroying the session when there is no user in it? IG you meant to put that destroy outside that condition.
@brc-dd sorry, this was intended to be simplified bit of code, not an excerpt from an actual application. I didn't catch that mistake with the user logic. I removed that conditional entirely to avoid confusion, while still replicating the bug.
For save/destroy to work you need to return the res object you gave it (or copy the headers from it to final response)
const res = NextResponse.redirect(new URL('/', req.url));
const session = await getIronSession(req, res, sessionOptions);
session.destroy();
return res;
@brc-dd thank you. Yes I did try await session.destroy()
, but per #571 I'm getting a type error there and even with await
it was not working.
@brc-dd per your follow up comment... 🙌... that was it! The copying of the header approach suited our use case best because we want to conditionally redirect depending on what we get back from getIronSession
.
export const middleware = async (req: NextRequest) => {
const res = NextResponse.next();
const session = await getIronSession(req, res, sessionOptions);
// other stuff...
session.destroy();
return NextResponse.redirect(new URL('/', req.url), { headers: res.headers });
};
Many many thank you's!