Next.js Discord

Discord Forum

Next.js with /Pages app with Graphql

Unanswered
Bonga shad posted this in #help-forum
Open in Discord
Bonga shadOP
Hi,

I have set up a new Next.js app that uses /pages structure which is connected with a Graphql server. While working on the authentication flow, when the user logs in, the server send back a cookie session. How can I read this value in Next.js so that the session persists across all pages?
I want the user to still be logged in when they refresh the page or navigate to a different website and back.

15 Replies

Cape horse mackerel
what are you using for auth?
Bonga shadOP
I've configured apollo server to send back a cookie and I can see the cookie being store in the browser
Cape horse mackerel
probably you can use nextjs middleware, or create a component that gets cookie via cookies function provided by nextjs, then wrap root layout with that component, if there is no cookie redirect to login, smth like that
Bonga shadOP
I've tried to use middlewares (created a middleware.js file in my root directory) but it didn't recognise it .
Cape horse mackerel
well, you can create a hook that will read the cookie, if there is no cookie, redirect to login page. Then if you want to protect let's say /dashboard route, you'd just call the hook there.
Another way is to create a component that will wrap all pages that needs to be protected
Bonga shadOP
I was thinking about doing that but I can't read the cookie value because it's an HttpOnly true cookie 😦
Cape horse mackerel
this is not maintained anymore but we have auth with graphaql
graphql
I prefer using separate REST endpoints though
but anyway using graphql doesn't change anything
you can still set cookies from a graphql response
I just don't remember the exact syntax
Bonga shadOP
ahh, thank you both! I'll have a look