Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Roadmap v8 #586

Closed
8 of 13 tasks
brc-dd opened this issue Apr 22, 2023 · 47 comments
Closed
8 of 13 tasks

Roadmap v8 #586

brc-dd opened this issue Apr 22, 2023 · 47 comments
Assignees

Comments

@brc-dd
Copy link
Collaborator

brc-dd commented Apr 22, 2023

Highlights

  • Support for Next.js App Dir (Routes + RSC)
  • Cleaner API (wrappers are removed)
  • Fully framework agnostic (no /next, /edge, /express sub-exports)
  • Supports Node.js, Deno and Bun
  • Better TS support (uses generics instead of module augmentation)
  • More clear error messages
  • More flexibility per save/destroy call

Refer the v8 branch for ongoing work.

x-ref: #574

TODO

  • docs
  • examples
    • node
    • deno
    • bun
    • lagon
    • next
  • tests
    • existing
    • new
  • CI
  • all contributors, renovate, etc.
  • support server actions!
@twonil-jordan-stout
Copy link

Not to be that guy... but is there an ETA on this?

We're currently ditching next-auth and have implemented our own impl of stateless cookies, but would rather have a "trusted" solution.

@brc-dd
Copy link
Collaborator Author

brc-dd commented May 27, 2023

The code part is done. Just the docs and Next.js example are left. I'm not getting much time, but if anyone wants to contribute docs, it would be great. I can release a v8-alpha though if you all are interested in testing it out.

@AlanMorel
Copy link

I'd like an alpha, would allow us to refactor our code to use the new API, and report bugs quicker.

Might even help with the docs too since as more implement it, we'd have more and more people with working examples of it in Next.js and other frameworks

@brc-dd
Copy link
Collaborator Author

brc-dd commented May 27, 2023

Cool, v8.0.0-alpha.0 is out! 🚀

PS: this is the examples link BTW: https://github.com/vvo/iron-session/tree/v8/examples
(npm is linking to main branch's examples directory)

@brc-dd brc-dd changed the title Roadmap v7 Roadmap v8 May 27, 2023
@emrosenf
Copy link

emrosenf commented May 27, 2023

This is how I got it working with next.js 13.4 server actions

lib/session.ts

import { cookies, headers } from 'next/headers';
import { getIronSession } from '@/lib/iron-session'

export interface Data {
  user?: {
    id: number
    name: string
  }
}

export const getSession = (req: any, res: any) => {
  const session = getIronSession<Data>(req, res, {
    password: 'ThisIsNotASecurePasswordPleaseChangeIt',
    cookieName: 'session',
    cookieOptions: {
      secure: true,
      maxAge: undefined,
    },
  })
  return session
}


export const getServerSession = async () => {
  const req = {
    headers: Object.fromEntries(headers() as Headers),
    cookies: Object.fromEntries(
      cookies()
        .getAll()
        .map((c) => [c.name, c.value]),
    ),
  };
  // @ts-ignore
  const res = { getHeader: headers().get, setCookie: cookies().set, setHeader: headers().set };
  const session = getSession(req, res)

  return session;
};

iron-session/core.ts L287

          (res as any).setCookie(mergedOptions.cookieName, seal, mergedOptions.cookieOptions)
          // setCookie(res, cookieValue)

This is a lazy, quick implementation that pinpoints the issue: setting headers is not yet supported in server actions. I hope one of you can come up with a more elegant solution.

@ErfanEbrahimnia
Copy link

Just in case someone wants to know how to use it in Next.js 13.4 Route Handlers:

  1. npm i iron-session@8.0.0-alpha.0
  2. Create a file to initialize iron-session (e.g. /my-libs/session.ts)
import { getIronSession, createResponse } from "iron-session";

export interface Data {
  user?: {
    id: number;
    name: string;
  };
}

export const getSession = (req: Request, res: Response) => {
  const session = getIronSession<Data>(req, res, {
    password: "ThisIsNotASecurePasswordPleaseChangeIt",
    cookieName: "session",
    cookieOptions: {
      secure: false,
    },
  });

  return session;
};

export { createResponse };
  1. Usage
// /app/api/some-endpoint.ts

import { NextRequest } from "next/server";
import { getSession, createResponse } from "@/my-libs/session";

export async function POST(request: NextRequest) {
  const response = new Response();
  const session = await getSession(request, response);

  session.user = {
    id: 1,
    name: "John Doe",
  };

  await session.save();

  return createResponse(
    response,
    JSON.stringify({ message: 'User created' })
  );
}

@yamijuan
Copy link

yamijuan commented May 31, 2023

Is there any example of how to get the session in a react server component?

@andershessellund
Copy link

I think the API could use some consideration. I created the following wrappers for use with next app router handlers. I think they are nicer to work with, but I am very new to next.js, so there could be issues with the approach.

Usage:

import { NextResponse } from "next/server";
import { getSession, setSession, withSession } from "../session/session";

interface Session {
  count?: number;
}

export const GET = withSession(async (request) => {
  const session = getSession<Session>();
  session.count = (session.count ?? 0) + 1;
  setSession(session);
  return NextResponse.json(session);
});

Implementation:

import { IronSessionOptions, getIronSession } from "iron-session";

const options: IronSessionOptions = {
  password: "complex_password_at_least_32_characters_long",
  cookieName: "my_app_cookie",
};

/**
 * extract session from request as plain JS object
 */
async function readSession<T>(request: Request) {
  const ironSession = await getIronSession(request, new Response(), options);
  // remove the save and destroy methods
  const session: any = {
    ...ironSession,
  };
  return session as T;
}

/**
 * Add the session cookie to a response object.
 */
async function writeSession<T>(session: T, response: Response) {
  const dummyRequest = new Request("http://dummy");
  const dummyResponse = new Response();
  const ironSession = await getIronSession(
    dummyRequest,
    dummyResponse,
    options
  );
  if (session) {
    Object.assign(ironSession, session);
    await ironSession.save();
  } else {
    await ironSession.destroy();
  }
  const cookieHeader = dummyResponse.headers.get("Set-Cookie");
  if (cookieHeader) {
    response.headers.set("Set-Cookie", cookieHeader);
  }
  return response;
}

const localStorage = new AsyncLocalStorage<[any]>();
type Handler = (request: Request) => Promise<Response>;

export function withSession(handler: Handler): Handler {
  return async (request: Request) => {
    const session = await readSession(request);
    localStorage.enterWith([session]);
    try {
      const response = await handler(request);
      const stored = localStorage.getStore()!;
      const newSession = stored[0];
      await writeSession(newSession, response);
      return response;
    } finally {
      localStorage.disable();
    }
  };
}

/**
 *
 * Return the session. Handler must be wrapped with withSession()
 */
export function getSession<T>(): T {
  const stored = localStorage.getStore();
  if (!stored) {
    throw new Error(
      "getSession() must be called from a handler wrapped with withSession()"
    );
  }
  return stored[0];
}

/**
 * Update the session.
 * @param session
 */
export function setSession<T>(session: T) {
  const stored = localStorage.getStore();
  if (!stored) {
    throw new Error(
      "setSession() must be called from a handler wrapped with withSession()"
    );
  }
  stored[0] = session;
}

@emrosenf
Copy link

emrosenf commented Jun 2, 2023

@yamijuan If you copy my example above, you can use getServerSession() in a RSC

export default async function Page() {

  const session = await getServerSession()
  if (!session.user) {
    redirect('/login')
  }

@mirsahib
Copy link

mirsahib commented Jun 4, 2023

Just in case someone wants to know how to use it in Next.js 13.4 Route Handlers:

  1. npm i iron-session@8.0.0-alpha.0
  2. Create a file to initialize iron-session (e.g. /my-libs/session.ts)
import { getIronSession, createResponse } from "iron-session";

export interface Data {
  user?: {
    id: number;
    name: string;
  };
}

export const getSession = (req: Request, res: Response) => {
  const session = getIronSession<Data>(req, res, {
    password: "ThisIsNotASecurePasswordPleaseChangeIt",
    cookieName: "session",
    cookieOptions: {
      secure: false,
    },
  });

  return session;
};

export { createResponse };
  1. Usage
// /app/api/some-endpoint.ts

import { NextRequest } from "next/server";
import { getSession, createResponse } from "@/my-libs/session";

export async function POST(request: NextRequest) {
  const response = new Response();
  const session = await getSession(request, response);

  session.user = {
    id: 1,
    name: "John Doe",
  };

  await session.save();

  return createResponse(
    response,
    JSON.stringify({ message: 'User created' })
  );
}

how do i create a protected route with the above implementation since the current iron-session version doesn't support the wrapper method withSessionSsr.
I have the following page to protect

import React from "react";

type Props = {
    user: {
        username: string;
        isAdmin: boolean;
    };
};

export default function Dashboard({ user }: Props) {
    return <div>{user.username}</div>;
}


@gerardnico
Copy link

Is there any example of how to get the session in a react server component?

May be with next/headers where you can access the headers of the incoming request and then the cookies that you can set in a middleware. Crazy.

@ChrisCates
Copy link

@mirsahib, I wouldn't worry about that. You actually don't want that. You should use middleware.ts to abstract protection of routes.

https://nextjs.org/docs/app/building-your-application/routing/middleware

@osdiab
Copy link

osdiab commented Jun 30, 2023

Is the official next example waiting on server actions stabilizing or something? Just hoping to have an official canonical example before I start on a new project in a month or so, not sure if I should hold my breath on that or not. Thanks!

@ChrisCates
Copy link

Hey @osdiab, check out my Printer project here: https://github.com/PrinterFramework/CLI

It's been stable in production so far for two applications that migrated. I would like to see some changes on Next.js's side for the query string. Also, it would be nice if iron-session support content types ahead of time. These are semantic and syntax changes though. Code works great and performs better than legacy router.

The following is a snippet using the API generator.

import { NextRequest, NextResponse } from 'next/server'
import { getSession, createResponse } from 'util/session'

export async function GET(req: NextRequest) {
  const res = new NextResponse()
  const session = await getSession(req, res)
  const { searchParams } = new URL(req.url)
  res.headers.set('Content-Type', 'application/json')

  try {
    return createResponse(
      res,
      JSON.stringify({
        status: 'OK',
        session
      }),
      { status: 200 }
    )
  } catch (error) {
    console.error(error)
    return createResponse(
      res,
      JSON.stringify({ status: 'ERROR', error }),
      { status: 500 }
    )
  }
}

@renchris
Copy link
Contributor

renchris commented Jul 1, 2023

Just in case someone wants to know how to use it in Next.js 13.4 Route Handlers:

  1. npm i iron-session@8.0.0-alpha.0
  2. Create a file to initialize iron-session (e.g. /my-libs/session.ts)
import { getIronSession, createResponse } from "iron-session";

export interface Data {
  user?: {
    id: number;
    name: string;
  };
}

export const getSession = (req: Request, res: Response) => {
  const session = getIronSession<Data>(req, res, {
    password: "ThisIsNotASecurePasswordPleaseChangeIt",
    cookieName: "session",
    cookieOptions: {
      secure: false,
    },
  });

  return session;
};

export { createResponse };
  1. Usage
// /app/api/some-endpoint.ts

import { NextRequest } from "next/server";
import { getSession, createResponse } from "@/my-libs/session";

export async function POST(request: NextRequest) {
  const response = new Response();
  const session = await getSession(request, response);

  session.user = {
    id: 1,
    name: "John Doe",
  };

  await session.save();

  return createResponse(
    response,
    JSON.stringify({ message: 'User created' })
  );
}

How do you call this some-endpoint response from a server component? I try to call it like this but I either get a react-server-dom-webpack-client.browser.development.js:1608 Uncaught TypeError: Failed to parse URL error or a FetchError: Unexpected token < in JSON at position 0 error if I do const response = await fetch('http://127.0.0.1:3000/api/some-endpoint', { cache: 'no-store' }) instead

const SomePage = async () => {
  const response = await fetch('/app/api/some-endpoint', { cache: 'no-store' })
  const data = await response.json()

  return (
    //jsx goes here
  )
}

export default SomePage

@renchris
Copy link
Contributor

I'm still trying to put this together in my head

How do I set the data

for example

session.user = {
id: 1,
name: "John Doe",
}

securely to cookies with this alpha release of Iron Session?

@renchris
Copy link
Contributor

renchris commented Jul 16, 2023

My get session function

import {
  IronSessionOptions, getIronSession,
} from 'iron-session'

const session = await getSession(request, response)

const getSession = async (req: Request, res: Response) => {
  const session = getIronSession(req, res, sessionOptions)
  return session
}

returns an empty object instead of a promise of the session object (with our fields and save and destroy functions)

would anyone know how I would get it to return a proper session object?

I just import IronSessionOptions from 'iron-session', right? I don't need to configure any middleware or anything. I couldn't find much more information or docs on the getSession function

-- EDIT --

Looking at the source code of getIronSession

function getCookie(req: RequestType, cookieName: string): string {
  return (
    parse(
      ('headers' in req && typeof req.headers.get === 'function'
        ? req.headers.get('cookie')
        : (req as IncomingMessage).headers.cookie) ?? ''
    )[cookieName] ?? ''
  )
}

async function getIronSession<T extends {} = {}>(
    req: RequestType,
    res: ResponseType,
    userSessionOptions: IronSessionOptions
  ): Promise<IronSession<T>> {

    //...

    const options = mergeOptions(userSessionOptions)
    const sealFromCookies = getCookie(req, options.cookieName)
    const session = sealFromCookies
      ? await unsealData<T>(sealFromCookies, { password: passwordsMap, ttl: options.ttl })
      : ({} as T)

    //...

    return session as IronSession<T>
  }

The function returns an empty string if there is not a cookie in the header of the request object. But how do I set the cookies to the headers in the first place? I thought that was what we use .save() in getIronSession for, but if I can't access getIronSession in the first place before setting the cookies, how do I set the cookies??

@ChrisCates
Copy link

@renchris, check this thread for a full reference code example. Try out https://prntr.click.

Best of luck.

@osdiab
Copy link

osdiab commented Jul 16, 2023

Given all the above discussion, and the apparent requirement to look at the source code of a different person's project just to figure out how to use this library with Next 13, hence I would love for there to be an official, canonical example in the documentation/repo that shows cut and dry how it's used.

As per my original question, barring other people's approaches, is there some blocker or issue preventing such an example from being present in iron-session itself besides time? Would someone like @ChrisCates be able to contribute that example if the maintainers don't have the time to put something together? Thanks! cc @brc-dd @vvo

@ycfreeman
Copy link

ycfreeman commented Jul 16, 2023

why not just make getCookie and setCookie configurable for createGetIronSession like pass them in as optional arguments, then we are all set -- seems we don't even need to care about req or res objects if we do that?

@ChrisCates
Copy link

@osdiab, I can throw in a vanilla example so that this can get merged into master.

Problem is will they respond. If they respond in this thread ill throw in a pull request.

If things get out of hand with the lack of responsiveness. Id hard fork the project btw. But, dont expect it to operate at the same scope it is right now. It would serve purely my own needs at Printer and not be as universal as it is in its current state.

@renchris
Copy link
Contributor

@ChrisCates are you using server actions?

I still haven't been able to get the expected behaviour of the cookies being stored on the client-side browser (where you can inspect page, go to the application tab, and see your cookies under the cookies column) to work.

However, when re-creating a minimal example of set cookies with server actions turned off, the cookies do get set back on the client side

@ChrisCates
Copy link

@renchris at the moment, no, I can work on an integration later. Looks neat.

@renchris
Copy link
Contributor

Getting and setting cookies in a Server Action works with { cookies } from 'next/headers'. I would like to modify the .save() and .destroy() functions of iron-session to use cookies in place of req.headers.get() and res.headers.append() to allow for support for NextJS app router and Server Actions. However, iron-session isn't a NextJS project itself and won't have access to { cookies } from 'next/headers'. Any advice on how to refactor the source code? I would love to get this to work, and then provide an Next example and docs, and get this v8 completed

Here is a snippet example of using cookies in Server Action in a 'use server' server-side environment file in a NextJS project

//src/app/actions.ts
'use server'

import { cookies } from "next/headers"

export const submitCookieToStorageServerAction = async (cookie: string) => {
  cookies().set('cookieName', cookie)
}

export const readCookieToStorageServerAction = async (): Promise<string> => {
  const cookieStore = cookies()
  const currentCookie = cookieStore.get('cookieName')
  return currentCookie ? currentCookie.value : 'Cookie Not Found!'
}

@luisalrp
Copy link

Not to be that guy... but is there an ETA on this?

We're currently ditching next-auth and have implemented our own impl of stateless cookies, but would rather have a "trusted" solution.

Hey @twonil-jordan-stout, I was looking for something similar. Any examples about it?

@renchris
Copy link
Contributor

Hey everyone 👋

I have Iron Session now fully working with support for NextJS App Router and Server Actions.

We have a new get iron session method getServerActionIronSession that utilizes the cookies() function from next/headers to set the cookies. This allows Iron Session to be used in Server Actions and React Server Components.

I have the feature update available as a pull request here: feat(v8): nextJS server action and react server component support #607

Documentation and a working NextJS example application have been provided. The example application shows both access patterns of API Route Handlers with getIronSession and Server Actions with getServerActionIronSession.

Please refer to my fork of the V8 branch for the updated Iron Session library and its examples/next folder for the NextJS example application.

To run the example application, checkout the v8 branch, then build the root Iron Session project with the pnpm package manager with pnpm install and pnpm build, then move into the examples/next folder with cd examples/next/, then run the example application with pnpm dev. Alternatively, the example application is available separately here: App Router with Iron Session

I would love your support in getting this PR approved so that we can complete this V8 branch to be pushed into the main branch for everyone to use.

cc: @vvo @brc-dd

@jotatoledo
Copy link

Hi everyone,

would be great if both the req/res types could also be exported https://github.com/vvo/iron-session/blob/v8/src/core.ts#L8C1-L9C46

@devjmetivier
Copy link

@renchris I noticed an issue with setServerActionCookie in that it doesn't pass along any cookie options when setting cookies in Server Actions. I've made this PR against your fork to resolve it:

renchris#1

Looking forward to getting this across the finish line for v8. We're excited to use it.

cc: @vvo @brc-dd

@renchris
Copy link
Contributor

renchris commented Oct 4, 2023

Hi Devin.

We pass in the cookie options as a parameter when we initialize the Iron Session object with sessionOptions: IronSessionOptions and we may include optional override options when we call .save() as saveOptions and .destroy() as destroyOptions in the type of OverridableOptions = Pick<IronSessionOptions, 'cookieOptions' | 'ttl'>

I provided a more detailed explanation under your PR on the fork.

Likewise, I hope @vvo and @brc-dd acknowledges so that we may complete and push the V8 branch to the main branch for us all to use.

🙂

@sizilio
Copy link

sizilio commented Oct 7, 2023

Hey guys!

I have a question, if anyone can help me, I would really appreciate it!

I installed the beta version of iron-session (yarn add iron-session@8.0.0-alpha.0), I'm trying to implement what @renchris indicated, but it keeps giving me the error:

Attempted import error: 'getServerActionIronSession' is not exported from 'iron-session'

Do I need to force the installation of a different version? Thanks.

@ChrisCates
Copy link

@sizilio you will need to use yarn add on his github fork.

See this Stack Overflow issue for more clarity.

@sizilio
Copy link

sizilio commented Oct 8, 2023

@sizilio you will need to use yarn add on his github fork.

See this Stack Overflow issue for more clarity.

Thank you for your help @ChrisCates

But I couldn't do what you suggested. Could you explain to me step by step how to do this?

i am dumb lol

@ChrisCates
Copy link

@sizilio, here,this should help. I haphazardly sent shitty StackOverflow responses assuming it would be concise. Here is a concise answer to help you.

Make sure to specify the branch after the hashtag, in this case it's the branch v8.

"dependencies": {
  ...
  "iron-session": "github:renchris/iron-session#v8",
  ...
}

@sizilio
Copy link

sizilio commented Oct 8, 2023

@sizilio, here,this should help. I haphazardly sent shitty StackOverflow responses assuming it would be concise. Here is a concise answer to help you.

Make sure to specify the branch after the hashtag, in this case it's the branch v8.

"dependencies": {
  ...
  "iron-session": "github:renchris/iron-session#v8",
  ...
}

Hi @ChrisCates, sorry to bother you again.

Bro, I tried to do what you asked for, I changed my package.json, I ran npm i, but whenever I run the project the error appears that iron-session was not found.

image

And look how strange the iron-session in node_modules was:

image

:'(

@ChrisCates
Copy link

ChrisCates commented Oct 8, 2023

@sizilio, can you try the following:

  1. Remove package-lock.json, node_modules and run npm install again

  2. If that doesn't work remove package-lock.json, node_modules and yarn.lock if it exists. And then run yarn.

If neither solution works. I can't comment and say I know the solution. Sorry. I am not able to reproduce this and I used both node v16 and v18.

@sizilio
Copy link

sizilio commented Oct 8, 2023

Thanks for the help @ChrisCates. I tried everything you advised, and I searched for help on the internet too, but the problem continues for me.

I'll wait to update the version in the original repository. I hope it does not take long :)

You are the best! Thank you anyway

@renchris
Copy link
Contributor

renchris commented Oct 9, 2023

Hi @sizilio. In the meantime while we wait for V8 to be merged into main, to use the Iron Session Server Action object, please use the dependency "iron-session": "github:renchris/iron-session#v8-as-dependency" for the dependancy.

You may refer to the example project App Router With Iron Session's package.json

{
  "name": "app-router-with-iron-session",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@types/node": "20.4.2",
    "@types/react": "18.2.15",
    "@types/react-dom": "18.2.7",
    "eslint": "8.45.0",
    "eslint-config-next": "13.4.10",
    "iron-session": "github:renchris/iron-session#v8-as-dependency",
    "next": "13.4.10",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "5.1.6"
  }
}

@sizilio
Copy link

sizilio commented Oct 9, 2023

Hi @sizilio. In the meantime while we wait for V8 to be merged into main, to use the Iron Session Server Action object, please use the dependency "iron-session": "github:renchris/iron-session#v8-as-dependency" for the dependancy.

You may refer to the example project App Router With Iron Session's package.json

{
  "name": "app-router-with-iron-session",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@types/node": "20.4.2",
    "@types/react": "18.2.15",
    "@types/react-dom": "18.2.7",
    "eslint": "8.45.0",
    "eslint-config-next": "13.4.10",
    "iron-session": "github:renchris/iron-session#v8-as-dependency",
    "next": "13.4.10",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "5.1.6"
  }
}

Niiiiice man @renchris! Now it worked! Thank you very much!

@renchris
Copy link
Contributor

Hi everyone 👋

I have Server Action Iron Session's .save() and .destroy() functions now fixed to properly take in and reflect changes from cookieOptions thanks to @devjmetivier

I have the fix update available as a pull request here: fix(v8): server action cookie options #617

Documentation has been provided along with a few other improvements.

I also have my fork branch "github:renchris/iron-session#v8-as-dependency" updated accordingly, so if you're using that in the meantime, you can update the dependency with your package manager (ex. pnpm update iron-session) to re-install the package dependency to reflect the fix changes as well.

@westlakem
Copy link

Not to be that guy, but the code has been done for a long time and we're just waiting on documentation? Can we please get this moved to an official release?

@vvo
Copy link
Owner

vvo commented Nov 15, 2023

Hey there, I am working on this v8 as we speak, you can expect a full release tomorrow EOD Paris time 👍

@vvo
Copy link
Owner

vvo commented Nov 16, 2023

Small note for anyone excited, the final version is coming tomorrow Friday 17th EOD (had to delay one day) 🙏

@vvo
Copy link
Owner

vvo commented Nov 18, 2023

Hey there, I just released a beta release. The API of this beta release will be the final one, so you can start using it in production.

pnpm add iron-session@8.0.0-beta.6

Usage: https://github.com/vvo/iron-session/tree/v8#usage

New discussion to finish rough edges: #620. Please keep it focused, thanks.

@vvo
Copy link
Owner

vvo commented Nov 20, 2023

iron-session v8 is live now 👍 https://github.com/vvo/iron-session

@vvo vvo closed this as completed Nov 20, 2023
@rossille
Copy link

Hey there, thanks for the awesome work !
Did the express middleware go in another package or was it simply removed ?

@vvo
Copy link
Owner

vvo commented Nov 24, 2023

@rossille there's no more express middleware, indeed. To get the same middleware you can do this:

import type { SessionOptions, IronSession } from "iron-session";
import { getIronSession } from "iron-session";
import type { Request, Response, NextFunction } from "express";

// typing of req.session elsewhere:
declare module "http" {
  interface IncomingMessage {
    session: IronSession<{ userId: number }>;
  }
}

// middleware
export function ironSession(
  sessionOptions: IronSessionOptions,
): (req: Request, res: Response, next: NextFunction) => Promise<void> {
  return async function ironSessionMiddleware(req, res, next) {
    req.session = await getIronSession(req, res, sessionOptions);
    next();
  };
}

Hope this helps 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests