Next.js Discord

Discord Forum

How to get session in middleware and move code from getServerSideProps.

Unanswered
Honded posted this in #help-forum
Open in Discord
I'm in a weird situation right now.

So far, to protect my pages, I was calling the function protectNextPage in getServerSideProps like this ASIDE from doing other stuff:

export async function getServerSideProps (context: GetServerSidePropsContext) { const redirect = await protectNextPage(context, 'myPermissionString') // every permission is different based on the page and the argument is a hardcoded string. if (redirect) return redirect // some other code that makes use of session and context object such getting the cookie from context.req.headers and call API endpoint to fetch data }

protectNextPage defitinion:
export async function protectNextPage (context: GetServerSidePropsContext, permission: string[] | string) { const session = await getServerSession(context.req, context.res, authOptions) if (!session || !session.user) { // redirect to entry page } // logic for handling permissions }

Now due to project requirements all pages need to be statically generated, so I'm changing every instance of getServerSideProps to getStaticProps and I'm using middlewares. Here's where I'm confused:

Session handling in middleware:
How can I obtain the session using getServerSession in middleware as previously done in getServerSideProps? if not possible, is there a replacement for getServerSession when dealing with middlewares?

Custom argument for my protectNextPage function:
- How can I call my protectNextPage in middleware with dynamic custom string arguments based on the page?
- How can I call the corresponding API endpoint based on the page and pass it the cookie?

0 Replies