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

Fix updates to session not reflected in async getServerSideProps #843

Merged
merged 3 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/helpers/get-server-side-props-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ export type GetServerSidePropsWrapper<P = any, Q extends ParsedUrlQuery = Parsed
*/
export default function getServerSidePropsWrapperFactory(getSessionCache: () => SessionCache) {
return function getServerSidePropsWrapper(getServerSideProps: GetServerSideProps): GetServerSideProps {
return function wrappedGetServerSideProps(...args) {
return async function wrappedGetServerSideProps(...args) {
const sessionCache = getSessionCache();
const [ctx] = args;
sessionCache.init(ctx.req, ctx.res, false);
const ret = getServerSideProps(...args);
const ret = await getServerSideProps(...args);
sessionCache.save(ctx.req, ctx.res);
return ret;
};
Expand Down
21 changes: 21 additions & 0 deletions tests/helpers/with-page-auth-required.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,25 @@ describe('with-page-auth-required ssr', () => {
const [cookie] = headers['set-cookie'];
expect(cookie).toMatch(/^appSession=/);
});

test('save session when getServerSideProps completes async', async () => {
const baseUrl = await setup(withoutApi, {
withPageAuthRequiredOptions: {
async getServerSideProps(ctx) {
await Promise.resolve();
const session = (global as any).getSession(ctx.req, ctx.res);
session.test = 'Hello World!';
return { props: {} };
}
}
});
const cookieJar = await login(baseUrl);

const {
res: { statusCode }
} = await get(baseUrl, '/protected', { cookieJar, fullResponse: true });
expect(statusCode).toBe(200);
const session = await get(baseUrl, '/api/session', { cookieJar });
expect(session.test).toBe('Hello World!');
});
});