iron-session icon indicating copy to clipboard operation
iron-session copied to clipboard

Getting bad usage, Minimum usage is const session = await getIronSession(...)

Open swtmply opened this issue 2 years ago • 3 comments

I'm using iron-session/next in my login api route I'm getting this error whenever I try logging in.

This is the code I'm using

import type { NextApiRequest, NextApiResponse } from "next";
import query from "../../lib/db";
import bcrypt from "bcrypt";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "../../lib/session";

export default withIronSessionApiRoute(loginRoute, sessionOptions);

async function loginRoute(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "POST") {
    try {
      const user: any = await query({
        query: "SELECT * FROM users WHERE email=?",
        values: [req.body.email],
      });

      const isMatched = await bcrypt.compare(
        req.body.password,
        user[0].password.replace("$2y$", "$2a$")
      );

      if (!isMatched)
        res
          .status(400)
          .json({ message: "Invalid Credentials, Please try again." });

      if (user.length === 0)
        res.status(401).json({ message: "User is not found" });

      req.session.user = user;
      await req.session.save();

      res.status(200).json({ ok: true });
    } catch (error) {
      res.status(500).json({ message: (error as Error).message });
    }
  }
}

swtmply avatar Apr 11 '22 05:04 swtmply

If you follow the instruction, use withIronSessionApiRoute and req.session.save(), it won't work!. However, it works in withIronSessionSsr.

chuyihuang avatar Apr 21 '22 08:04 chuyihuang

Hey there, I just tried the instructions again here: https://github.com/vvo/iron-session#nextjs-withironsessionapiroutehandler-ironoptions--req-nextapirequest-res-nextapiresponse--ironoptions--promiseironoptions

and it worked all good.

Can you console.log(sessionOptions), remove the secret and paste them here? Thanks

vvo avatar Apr 22 '22 21:04 vvo

I was facing the same issue. This solution works perfectly for me:

/lib/auth/session.js

import { withIronSessionApiRoute, withIronSessionSsr  } from "iron-session/next";

const sessionOptions = {
    cookieName: "userSession",
    password: process.env.SECRET_COOKIE_PASSWORD,
    cookieOptions: {
        secure: process.env.NODE_ENV === "production",
    },
};
 
export function withSessionSSR(handler) {
    return withIronSessionSsr(handler, sessionOptions)
}

export function withSessionAPI(handler) {
    return withIronSessionApiRoute(handler, sessionOptions)
}

/pages/api/auth/login

import axios from "axios";
import { API_URL } from "../../../lib/apiChanger";
import { withSessionAPI } from "../../../lib/auth/session";

export default withSessionAPI(
    async (req, res)=> {

        const {identifier, password} = req.body;

        // Log in via Strapi and get user + JWT
        const { data } = await axios.post(`${API_URL}/api/auth/local`, {
            identifier, password
        })

        req.session.user = await data;
        await req.session.save();
        res.status(200).json({success: "Logged in"});

    }
)

nordowl avatar Jun 16 '22 13:06 nordowl

Hi, had same error but was my mistake. I opened a new terminal and forgot to set SECRET_COOKIE_PASSWORD

export SECRET_COOKIE_PASSWORD = xxxxxxxxxxxx

karelbecerra avatar Nov 20 '22 23:11 karelbecerra

It would be really helpful if the error message correctly identified the missing env var. Current error is absolutely impossible to debug.

zedrdave avatar Mar 10 '23 19:03 zedrdave

Adding an environment variable works for me, but I have to add a prefix to it for NextJS project:

IRON_SESSION_SECRET=

gamertense avatar Mar 25 '23 18:03 gamertense

I got same error, resolve this by adding environment variable. If password is undefined, it will throw this error.

jkiss avatar Apr 10 '23 06:04 jkiss