i've got this middleware function but it doesn't work :
import { NextApiRequest, NextApiResponse } from 'next';
export async function middleware(handler: any, req: NextApiRequest, res: NextApiResponse) {
const sessionCookie = req.cookies.get('session');
if (!sessionCookie) {
// If the session cookie is invalid or missing, redirect to the home page
res.writeHead(302, { Location: '/home' });
res.end();
return null; // Return null to avoid returning undefined
}
// If the session cookie is valid, allow access to the route
return await handler(req, res);
}
and i get the error :
Server Error
TypeError: Cannot read properties of undefined (reading 'get')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
how can i solve this ?