iron-session
iron-session copied to clipboard
Iron session with graphql
Hi, Is it possible to use iron-session with graphql apollo server?
Also very interested in using this with @apollo/client
Also been trying to figure this out 🤔
Any pointers/suggestions on how to use @apollo/client with the V8 update for Server Actions
Hey there, can you provide specific details of what you're trying to achieve, what worked and what failed? Thanks!
Will try the new release first and will get back to you! It has been a couple of days since ive tried it so i dont remember the finer details.
This is on the new V8 release my current setup is a /src/api/graphql route as follows:
import { cookies } from 'next/header'
import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { getIronSession } from 'iron-session'
import db from '@/next/server/sequelize/startDB'
import sessionOptions from '@/next/lib/sessionOptions'
import { schema } from '@/next/lib/graphql'
const server = new ApolloServer({ schema, introspection: process.env.NODE_ENV !== 'production' })
const handler = startServerAndCreateNextHandler(server, {
context: async (req, res) => {
const session = await getIronSession(cookies(), sessionOptions)
const { username } = session
const user = username && await db.models.user.findByPk(username)
return { username, user, session }
}
})
export { handler as GET, handler as POST }
a /lib/getSession file:
'use server'
import { getIronSession } from 'iron-session'
import { cookies } from 'next/headers'
import sessionOptions from './sessionOptions'
const getSession = getIronSession(cookies(), sessionOptions)
export default getSession
and when using it on an action like this:
export async function login (formData) {
try {
const session = await getSession()
const client = await getClient()
const username = formData.get('username')
const password = formData.get('password')
const user = await db.models.user.findByPk(username)
if (!user) throw loginError
const valid = await bcrypt.compare(password, user.password)
if (!valid) throw loginError
session.username = user.username
await session.save()
client.resetStore()
return { ok: true }
} catch (err) {
return { ok: false, message: err.message }
}
}
The following error happens on dev mode page build:
Hey @jorgev259 you can see a live example of using cookies() with iron session here: https://get-iron-session.vercel.app/app-router-server-component-and-action. Open a different issue if this is unrelated to graphql. Thanks!
I believe you issue is that you call cookies() too early here.
I am gonna close this for now. If you happen to try to use iron-session with any GraphQL tooling and it fails because of how iron-session is being written, please open a new issue with a reproducible repository where I can have a look. Thanks!