react-oidc-context icon indicating copy to clipboard operation
react-oidc-context copied to clipboard

How to receive session on server side

Open loki344 opened this issue 1 year ago • 1 comments

Hi

I'm trying to use this library in a Next.js project. Currently we are using the pages directory. I have no problem to receive the session data on the client side. But using the getServerSideProps to fetch data from a protected API seems rather difficult.

My first try was to write the acces_token as a cookie everytime the session is refreshed on the client. This would then be sent to the server with the request and can there be used to fetch the data.

const Faq: NextPage<FaqProps> = ({faqs}) => {
    const auth = useAuth()
    React.useEffect(() => {
        console.log(auth?.user?.access_token, 'new access token')
        if (auth.user) {
            document.cookie = `access_token=${auth.user.access_token}`
        } else {
            //revoke cookie
        }
    }, [auth?.user?.access_token])
    return <FaqPage faqs={faqs}></FaqPage>;
};
export const getServerSideProps: GetServerSideProps<FaqProps> = async (context) => {
    const { serverRuntimeConfig } = getConfig();

    console.log(context.req);

    const access_token = context.req.cookies.access_token;

    // fetching some data with the access_token

    return {
        props: {
            faqs: ...
        }
    };
};
export default Faq;

For reference my provider:

const onSigninCallback = (user: void | User): void => {
        router.replace(
            window.location.pathname
        )
    }
    const oidcConfig: AuthProviderProps = {
        authority: "xx",
        client_id: 'xx',
client_secret: 'xxx',
        redirect_uri: typeof window !== 'undefined' ? window.location.href : '',
        automaticSilentRenew: true,
    };

<AuthProvider {...oidcConfig} onSigninCallback={onSigninCallback}
                                          userStore={
                                              new WebStorageStateStore({
                                                  store: globalThis?.window?.localStorage ?? InMemoryWebStorage
                                              })
                                          }
                                          children={children}/>

This does work, but only as long as the access_token is valid. Leaving the browser open but inactive for a while, coming back to the window and hitting F5 caused a request with an outdated acces_token in the cookies, and the server is then not able to refresh it on its own.

My second though was to migrate to the app directory, as I saw some threads on github mentioning ssr support. But how can i get access to the session in a server component to fetch data? I cannot use the 'useAuth' hook as it's only available client-side.

Are there any working examples for next.js or react server side components in general?

Some assistance would be very appreciated.

Greetings

loki344 avatar Oct 24 '23 14:10 loki344

I have no experience in next.js/SSR. The access token is used in-between client and server. getServerSideProps on the other hand is executed on the server side. Thus i would try to avoid using a access token in that case.

pamapa avatar Oct 25 '23 07:10 pamapa