Manually create a session

Hi, for testing purposes I want to create a session in my own controller, and set the right cookies. Although, it seems like the sesison token has to be in a certain structure. Has anyone got a better idea on how I can implement this?
The cookie names do match, I am using NextJS so I would need a backend approach to create the sessions.

      // Create or get the test user
      const user = await plainPrisma.user.upsert({
        where: { email: STAGING_EMAIL },
        update: {},
        create: {
          email: STAGING_EMAIL,
          name: "Staging Test",
        },
      });

      // Create a session
      const session = await plainPrisma.session.create({
        data: {
          token: nanoid(64),
          userId: user.id,
          userAgent: "Playwright",
          ipAddress: "::1",
          expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours from now
        },
      });

      const secureCookie = true;

      // Set cookie through Next.js API
      const cookieStore = await cookies();
      cookieStore.set("better-auth.session_token", session.token, {
        expires: session.expiresAt,
        httpOnly: true,
        secure: secureCookie,
        sameSite: "lax",
        path: "/",
      });

      cookieStore.set("__Secure-better-auth.session_token", session.token, {
        expires: session.expiresAt,
        httpOnly: true,
        secure: secureCookie,
        sameSite: "lax",
        path: "/",
      });
Solution
hmm...you can fill it with those details -

import { createRandomStringGenerator } from "@better-auth/utils/random";
import { createHMAC } from "@better-auth/utils/hmac";



const user = await plainPrisma.user.upsert({
  where: { email: STAGING_EMAIL },
  update: {},
  create: {
    email: STAGING_EMAIL,
    name: "Staging Test",
  },
});


export const generateId = (size?: number) => {
    return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32);
};


const sessionToken = nanoid(64);
const session = await plainPrisma.session.create({
  data: {
    id: sessionToken, 
    token: sessionToken,
    userId: user.id,
    userAgent: "Playwright",
    ipAddress: "::1",
    expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours from now
    createdAt: new Date(),
    updatedAt: new Date(),
  },
});

const signedToken = await createHMAC("SHA-256", "base64urlnopad").sign(
  process.env.BETTER_AUTH_SECRET!, // Your Better Auth secret
  sessionToken
);

// Set the cookies
const cookieStore = await cookies();
const secureCookie = process.env.NODE_ENV === "production";

// Set the main session cookie
cookieStore.set("better-auth.session_token", signedToken, {
  expires: session.expiresAt,
  httpOnly: true,
  secure: secureCookie,
  sameSite: "lax",
  path: "/",
});

// Set the secure cookie if in production
if (secureCookie) {
  cookieStore.set("__Secure-better-auth.session_token", signedToken, {
    expires: session.expiresAt,
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    path: "/",
  });
}


this is what the better auth does internally .. for more utils please make sure to visit https://github.com/better-auth/utils
GitHub
A simple typescript API for common auth related operations built on top of Web Crypto API. - better-auth/utils
Was this page helpful?