Comments (7)
@viachaslau-latushkin ➡️ vercel/next.js#49442 (comment)
from iron-session.
You can use sealData() and unsealData() to encrypt/decrypt the cookie values.
Assuming you're doing an oauth/refresh token kind of thing, here's something I used recently:
import {
IRON_COOKIE_NAME,
SessionData,
ironOptions,
} from './auth';
export async function middleware() {
const session = await getIronSession<SessionData>(cookies(), ironOptions);
const next = NextResponse.next();
if (!session.token?.expires_at) {
// no/invalid token, send user to auth
return NextResponse.redirect(getGoogleAuthURL());
}
if (session.token.expires_at < Date.now()) {
// refresh token
try {
const token = await refreshToken(session.token);
const sealed = await sealData(
{
...session,
token: { ...token, expires_at: Date.now() + token.expires_in * 1000 },
},
ironOptions,
);
next.cookies.set(IRON_COOKIE_NAME, sealed);
// await session.save(); // won't work
} catch (e) {
// some error while refreshing token, send user to auth
console.error(e);
return NextResponse.redirect(getGoogleAuthURL());
}
}
return next;
}
from iron-session.
Thank you!
But in this case cookie from middleware is not encrypted.
from iron-session.
Hello @viachaslau-latushkin ,
iron-session adds the encrypted cookie via the "set-cookie" header, so the applySetCookie method applies the correctly encrypted cookie!
What makes you think otherwise?
from iron-session.
@Thanaen in middleware I am trying to apply refresh token logic.
I get a new token and try to rewrite cookie with new encrypted (encrypted token) value.
Yes, applySetCookie really add new cookie from middleware and it exists in next steps.
But how get new encrypted value with help of iron-session which will be encrypted in middleware with help of sessionOptions.password and after successfully decrypt this value (again with help of sessionOptions.password) in time of SSR or in Api Router handler?
from iron-session.
@arthurjdam
Thank you.
Nice solution.
And good point to read documentation from start to end.
from iron-session.
As @arthurjdam solution, here's the updated version that worked for me. Hope it may save time for others.
This solution fixes the error Cookies can only be modified in a Server Action or Route Handler
after calling the await session.save()
.
middleware.ts
export default async function middleware(req: NextRequest) {
const { isLoggedIn, exp } = await getSession();
// Refresh Token Rotation
if (isLoggedIn && exp && exp < Date.now() / 1000) {
try {
const newSession = await refreshToken();
const sealed = await sealData(newSession, sessionOptions);
const res = NextResponse.redirect(req.url);
res.cookies.set({
name: '[your-cookie-name]',
value: sealed,
});
return res;
} catch (e) {
await logout();
}
}
return NextResponse.next();
}
authActions.ts
export async function getSession() {
return await getIronSession<User>(cookies(), sessionOptions);
}
export async function refreshToken() {
const session = await getSession();
const res = await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_BASE_URL}/user/refresh`,
{
method: 'POST',
headers: { Authorization: 'Bearer ' + session.refreshToken },
}
);
const { accessToken, refreshToken } = await res.json();
const newUser = jwt.decode(accessToken) as JwtPayload;
session.userToken = accessToken;
session.refreshToken = refreshToken;
session.exp = newUser.exp;
return session;
}
P.S. I'm assuming the interface of my User
object is:
export interface User {
id: string;
isLoggedIn: boolean;
name: string;
userToken: string;
refreshToken: string;
exp: number | undefined;
}
I'm available for any further clarifications or inquiries...
from iron-session.
Related Issues (20)
- v8 beta release, last tasks and discussions HOT 6
- session object empty on Apollo Server API Route
- Can i use iron-session with pages routes ? HOT 1
- Implementing iron-session with TRPC HOT 9
- Session cookie not created when static web app is sitting behind azure front door due to domain mismatch HOT 3
- Static maxAge
- v8 - Attaching session to request HOT 1
- Make properties in T for IronSession<T> optional (union with undefined)
- Migration away from `withIronSessionApiRoute` HOT 3
- await session.save() fails to set cookie if cookies.set() is used after HOT 2
- session returned from `getIronSessionFromCookieStore` does not implement full interface HOT 1
- outdated dependency @types/cookie causes type mismatch HOT 1
- why getIronSession not work in middleware like in example (App router + client components, route handlers, and SWR) HOT 3
- Support the `partitioned` attribute in cookie settings HOT 1
- Discrepancy in documentation of password rotation. HOT 5
- Next.js middleware token rotation issue HOT 3
- Unable to create a session cookie HOT 3
- How to access stored sessions of my users?
- TypeError: session.updateConfig is not a function
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from iron-session.