-
-
Notifications
You must be signed in to change notification settings - Fork 252
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
Comments
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. |
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. |
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 |
Cool, PS: this is the examples link BTW: https://github.com/vvo/iron-session/tree/v8/examples |
This is how I got it working with next.js 13.4 server actions lib/session.ts
iron-session/core.ts L287
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. |
Just in case someone wants to know how to use it in Next.js 13.4 Route Handlers:
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 };
// /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' })
);
} |
Is there any example of how to get the session in a react server component? |
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;
} |
@yamijuan If you copy my example above, you can use
|
how do i create a protected route with the above implementation since the current iron-session version doesn't support the wrapper method
|
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. |
@mirsahib, I wouldn't worry about that. You actually don't want that. You should use https://nextjs.org/docs/app/building-your-application/routing/middleware |
Is the official |
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 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 }
)
}
} |
How do you call this some-endpoint response from a server component? I try to call it like this but I either get a
|
I'm still trying to put this together in my head How do I set the data for example session.user = { securely to cookies with this alpha release of Iron Session? |
My get session function
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
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?? |
@renchris, check this thread for a full reference code example. Try out https://prntr.click. Best of luck. |
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 |
why not just make |
@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. |
@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 |
@renchris at the moment, no, I can work on an integration later. Looks neat. |
Getting and setting cookies in a Server Action works with Here is a snippet example of using cookies in Server Action in a 'use server' server-side environment file in a NextJS project
|
Hey @twonil-jordan-stout, I was looking for something similar. Any examples about it? |
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 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 Please refer to my fork of the V8 branch for the updated Iron Session library and its To run the example application, checkout the 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. |
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 |
@renchris I noticed an issue with Looking forward to getting this across the finish line for v8. We're excited to use it. |
Hi Devin. We pass in the cookie options as a parameter when we initialize the Iron Session object with 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. 🙂 |
Hey guys! I have a question, if anyone can help me, I would really appreciate it! I installed the beta version of iron-session (
Do I need to force the installation of a different version? Thanks. |
@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 |
@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 "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 And look how strange the iron-session in :'( |
@sizilio, can you try the following:
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. |
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 |
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 You may refer to the example project App Router With Iron Session's
|
Niiiiice man @renchris! Now it worked! Thank you very much! |
Hi everyone 👋 I have Server Action Iron Session's 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 |
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? |
Hey there, I am working on this v8 as we speak, you can expect a full release tomorrow EOD Paris time 👍 |
Small note for anyone excited, the final version is coming tomorrow Friday 17th EOD (had to delay one day) 🙏 |
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.
Usage: https://github.com/vvo/iron-session/tree/v8#usage New discussion to finish rough edges: #620. Please keep it focused, thanks. |
iron-session v8 is live now 👍 https://github.com/vvo/iron-session |
Hey there, thanks for the awesome work ! |
@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 👍 |
Highlights
Refer the v8 branch for ongoing work.
x-ref: #574
TODO
The text was updated successfully, but these errors were encountered: