import { withIronSession } from 'next-iron-session'; import type { Session } from 'next-iron-session'; import { IncomingMessage, ServerResponse } from 'http'; import { NextApiResponse, NextPageContext } from 'next'; import { DocumentContext } from 'next/document'; export interface IncomingMessageWithSession extends IncomingMessage { body: any; session: Session } export type HandlerWithDocumentContextAndSession = ( ctx: DocumentContext & { req: IncomingMessageWithSession }, ) => Promise; export type HandlerWithPageContextAndSession = ( ctx: NextPageContext & { req: IncomingMessageWithSession }, ) => Promise; export type HandlerWithReqResAndSession = ( req: IncomingMessageWithSession, res: NextApiResponse ) => Promise; export type HandlerWithSession = T extends IncomingMessageWithSession ? HandlerWithReqResAndSession : T extends NextPageContext ? HandlerWithPageContextAndSession : HandlerWithDocumentContextAndSession; export default function withSession( handler: ( req: IncomingMessageWithSession, res: NextApiResponse, ...args: any) => Promise, ): (...args: any) => Promise { return withIronSession(handler, { cookieName: 'gdq-archive', cookieOptions: { // the next line allows to use the session in non-https environements like // Next.js dev mode (http://localhost:3000) secure: process.env.NODE_ENV === 'production', httpOnly: true, }, password: process.env.SECRET_PASSWORD || '0'.repeat(32), }); }