Implement Next Auth (Auth.js) with Drizzle Adapter. (AWS RDS- POSTGRES)

Auth.js released thier official adapter for Drizzle . Thigs were supposed to be easy , we setup Next Auth , and just pass our db instance…

Implement Next Auth (Auth.js) with Drizzle Adapter. (AWS RDS- POSTGRES)

Auth.js released thier official adapter for Drizzle . Thigs were supposed to be easy , we setup Next Auth , and just pass our db instance to Drizzle Adapter and things were supposed to work , But things went side ways for me.

Initially i faced this issue . My Auth.JS Adapter type and Next Auth adapter type was incompatable. Though this was an easy fix from the team , The Release was scheduled for a later time , But i needed it immediately so i decided to take things in my own hands.

If you look at the code for official adapter they check which db you use and return the appropriate adapter (sql,postgres,sqlite) . I suggest you to pick your corresponding adapter. which was postrgres for me.

CHOOSE HERE

Once you have the adapter, its time to make it compatable with NEXT AUTH

Creating the schema

// db/schema.ts 
 
import { 
  pgTable, 
  text, 
  primaryKey, 
  integer, 
  timestamp 
} from "drizzle-orm/pg-core"; 
import type { AdapterAccount } from "@auth/core/adapters"; 
 
export const users = pgTable("user", { 
  id: text("id").notNull().primaryKey(), 
  name: text("name"), 
  email: text("email").notNull(), 
  emailVerified: timestamp("emailVerified"), 
  image: text("image"), 
}); 
 
export const accounts = pgTable( 
  "account", 
  { 
    userId: text("userId") 
      .notNull() 
      .references(() => users.id, { onDelete: "cascade" }), 
    type: text("type").$type<AdapterAccount["type"]>().notNull(), 
    provider: text("provider").notNull(), 
    providerAccountId: text("providerAccountId").notNull(), 
    refresh_token: text("refresh_token"), 
    access_token: text("access_token"), 
    expires_at: integer("expires_at"), 
    token_type: text("token_type"), 
    scope: text("scope"), 
    id_token: text("id_token"), 
    session_state: text("session_state"), 
  }, 
  (account) => ({ 
    compoundKey: primaryKey(account.provider, account.providerAccountId), 
  }) 
); 
 
export const sessions = pgTable("session", { 
  sessionToken: text("sessionToken").notNull().primaryKey(), 
  userId: text("userId") 
    .notNull() 
    .references(() => users.id, { onDelete: "cascade" }), 
  expires: timestamp("expires").notNull(), 
}); 
 
export const verificationTokens = pgTable( 
  "verificationToken", 
  { 
    identifier: text("identifier").notNull(), 
    token: text("token").notNull(), 
    expires: timestamp("expires").notNull(), 
  }, 
  (vt) => ({ 
    compoundKey: primaryKey(vt.identifier, vt.token), 
  }) 
);

I copied the schema from Auth.js Docs.

drizzle-adapter/index.ts

import { and, eq } from "drizzle-orm"; 
import { 
  pgTable as defaultPgTableFn 
} from "drizzle-orm/pg-core"; 
 
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js"; 
import { NextAuthOptions } from "next-auth"; 
import * as schema from "../db/schema"; 
type Adapter = NextAuthOptions["adapter"]; 
export function createTables() { 
  const users = schema.users 
 
  const accounts = schema.accounts 
 
  const sessions = schema.sessions 
 
  const verificationTokens = schema.verificationTokens 
  return { users, accounts, sessions, verificationTokens }; 
} 
 
export type DefaultSchema = ReturnType<typeof createTables>; 
 
export function pgDrizzleAdapter( 
  client: PostgresJsDatabase<Record<string, never>>, 
  tableFn = defaultPgTableFn 
): Adapter { 
  const { users, accounts, sessions, verificationTokens } = 
    createTables(); 
 
  return { 
    async createUser(data: any) { 
      return await client 
        .insert(users) 
        .values({ ...data, id: crypto.randomUUID() }) 
        .returning() 
        .then((res) => res[0] ?? null); 
    }, 
    async getUser(data: any) { 
      return await client 
        .select() 
        .from(users) 
        .where(eq(users.id, data)) 
        .then((res) => res[0] ?? null); 
    }, 
    async getUserByEmail(data: any) { 
      return await client 
        .select() 
        .from(users) 
        .where(eq(users.email, data)) 
        .then((res) => res[0] ?? null); 
    }, 
    async createSession(data: any) { 
      return await client 
        .insert(sessions) 
        .values(data) 
        .returning() 
        .then((res) => res[0]); 
    }, 
    async getSessionAndUser(data: any) { 
      return await client 
        .select({ 
          session: sessions, 
          user: users, 
        }) 
        .from(sessions) 
        .where(eq(sessions.sessionToken, data)) 
        .innerJoin(users, eq(users.id, sessions.userId)) 
        .then((res) => res[0] ?? null); 
    }, 
    async updateUser(data: any) { 
      if (!data.id) { 
        throw new Error("No user id."); 
      } 
 
      return await client 
        .update(users) 
        .set(data) 
        .where(eq(users.id, data.id)) 
        .returning() 
        .then((res) => res[0]); 
    }, 
    async updateSession(data: any) { 
      return await client 
        .update(sessions) 
        .set(data) 
        .where(eq(sessions.sessionToken, data.sessionToken)) 
        .returning() 
        .then((res) => res[0]); 
    }, 
    async linkAccount(rawAccount: any) { 
      const updatedAccount = await client 
        .insert(accounts) 
        .values(rawAccount) 
        .returning() 
        .then((res) => res[0]); 
 
      // Drizzle will return `null` for fields that are not defined. 
      // However, the return type is expecting `undefined`. 
      const account = { 
        ...updatedAccount, 
        access_token: updatedAccount.access_token ?? undefined, 
        token_type: updatedAccount.token_type ?? undefined, 
        id_token: updatedAccount.id_token ?? undefined, 
        refresh_token: updatedAccount.refresh_token ?? undefined, 
        scope: updatedAccount.scope ?? undefined, 
        expires_at: updatedAccount.expires_at ?? undefined, 
        session_state: updatedAccount.session_state ?? undefined, 
      }; 
 
      // return account; 
    }, 
    async getUserByAccount(account) { 
      const dbAccount = 
        (await client 
          .select() 
          .from(accounts) 
          .where( 
            and( 
              eq(accounts.providerAccountId, account.providerAccountId), 
              eq(accounts.provider, account.provider) 
            ) 
          ) 
          .leftJoin(users, eq(accounts.userId, users.id)) 
          .then((res) => res[0])) ?? null; 
 
      if (!dbAccount) { 
        return null; 
      } 
 
      return dbAccount.userAuth; 
    }, 
    async deleteSession(sessionToken) { 
      const session = await client 
        .delete(sessions) 
        .where(eq(sessions.sessionToken, sessionToken)) 
        .returning() 
        .then((res) => res[0] ?? null); 
 
      return session; 
    }, 
    async createVerificationToken(token) { 
      return await client 
        .insert(verificationTokens) 
        .values(token) 
        .returning() 
        .then((res) => res[0]); 
    }, 
    async useVerificationToken(token) { 
      try { 
        return await client 
          .delete(verificationTokens) 
          .where( 
            and( 
              eq(verificationTokens.identifier, token.identifier), 
              eq(verificationTokens.token, token.token) 
            ) 
          ) 
          .returning() 
          .then((res) => res[0] ?? null); 
      } catch (err) { 
        throw new Error("No verification token found."); 
      } 
    }, 
    async deleteUser(id) { 
      await client 
        .delete(users) 
        .where(eq(users.id, id)) 
        .returning() 
        .then((res) => res[0] ?? null); 
    }, 
    async unlinkAccount(account) { 
      const { type, provider, providerAccountId, userId } = await client 
        .delete(accounts) 
        .where( 
          and( 
            eq(accounts.providerAccountId, account.providerAccountId), 
            eq(accounts.provider, account.provider) 
          ) 
        ) 
        .returning() 
        .then((res) => res[0] ?? null); 
 
      // return { provider, type, providerAccountId, userId }; 
    }, 
  }; 
}

Instead of using two schemas like in Auth.js Docs , We will import our existing schema from schema.ts file , By this approach we have a single schema which can be managed easily from one place.

You just have to comment the return objects for link and unlink methods , because Next does’nt have them in their types yet , and you can see i have altered the type for the Adapter.

Once we have all these in place now ,Next Auth and Drizzle should be compatable …

Stick with me if you use AWS RDS POSTGRES

ADDITIONAL CONFIG (If you have hard time with config)

// src/app/api/auth/[…nextauth]/route.ts

import { authOptions } from "@/lib/auth"; 
import NextAuth from "next-auth"; 
 
const handler = NextAuth(authOptions); 
export { handler as GET, handler as POST };

IF YOU NEED HELP WITH NEXT 13

check out this blog post


ISSUE WITH AWS-DATA-API

If you use AWS with drizzle you will face an issue saying date cant be parsed. more info here

I decided to have a simple work around for this . so I uploaded the date as a string to the db and parsed it back as Date on retrieval.

This i how i used my custom data type

// drizzle-adapter/customType.ts 
import { customType } from "drizzle-orm/pg-core"; 
 
export const nextAuthDate = customType<{ 
  data: Date; 
  driverData: string; 
}>({ 
  dataType(config) { 
    return "text"; 
  }, 
  fromDriver(value: string): Date { 
    return new Date(value); 
  }, 
  toDriver(value: Date) { 
    return value.toISOString(); 
  }, 
});

Then update it in the schema

// db/schema.ts 
import { 
  pgTable, 
  text, 
  primaryKey, 
  integer, 
} from "drizzle-orm/pg-core"; 
import type { AdapterAccount } from "@auth/core/adapters"; 
import { nextAuthDate as timestamp } from "../drizzle-adapter/cutomDate";

Thats it , You now have drizzle with AWS RDS + POSTGRES