next-redux-wrapper icon indicating copy to clipboard operation
next-redux-wrapper copied to clipboard

Accessing store from NextJs middleware

Open robertodilillo opened this issue 3 years ago • 4 comments

Is your feature request related to a problem? Please describe. Currently there is no support to use state in middleware functions

Describe the solution you'd like NextJs 12 allows middleware. would be good

Describe alternatives you've considered the only alternative is to repeat the middleware logic in any index page or have it in the _app file which would exclude the automatic static optimization

Additional context here s an example

import { NextResponse } from 'next/server';
import { nextStore } from '@store/store';

export const middleware = nextStore.middleware((store) => async ({ req, query, res }) => {
	const { tick } = store.getState();
	console.log(tick);
	return NextResponse.next();
});

robertodilillo avatar Nov 03 '21 12:11 robertodilillo

refresh token need!

zhangwei900808 avatar Dec 14 '21 13:12 zhangwei900808

I actually digged into middlewares, and from what I saw they are only used for responses manipulation. So you are not able to pass any props to the code => meaning that you cannot return the new redux state. The only workaround that I kinda came with would be to use cookies for this, but that seems like an overkill...

HamAndRock avatar Dec 14 '21 13:12 HamAndRock

So you are not able to pass any props to the code => meaning that you cannot return the new redux state.

Valid point. I was in a rather niche situation recently though where just having a next-redux-wrapper-created store instance in a middleware would have been enough, since I was using my next-redux-cookie-wrapper thingy (which, I guess, is what @bryantobing12 and @zhangwei900808 are doing too).

bjoluc avatar Jul 23 '22 18:07 bjoluc

Any updates on this? I tried using getStaticProps internally in middleware and it looks like a possible solution. But the state after hydration remains default

gmonitoring avatar Nov 20 '23 14:11 gmonitoring