Marcelo Barros
Marcelo Barros

Reputation: 1048

Using Redis with Auth.js and Next.js Middleware on Edge Runtime: 'dns' Module Error

I'm using Auth.js (v5) as the authentication library in a Next.js application. I'm using Unstorage as a Database Adapter to store session data in a key-value storage. The storage works fine with In Memory storage, but that's not suitable for production, so I'm switching to Redis storage. Unstorage uses ioredis under the hood to connect to Redis.

Following the steps in all the official docs, I encounter the following error after starting the application:

Cannot read properties of undefined (reading 'charCodeAt')

Digging into the code (./node_modules/ioredis/built/cluster/ClusterOptions.js:4:1), I found that the error is due the fact that ioredis uses dns (and other) modules specific to Node.

Module not found: Can't resolve 'dns'

Since the authentication runs on middleware, which runs on the Edge Runtime, these modules are unavailable. Next.js's official docs suggest a workaround, but I don't see how it applies to Auth.js and middleware.

My question is: Is there a way to use Redis to store session and user info in a Next.js app running Auth.js? Am I missing something?

Versions:

Steps to reproduce:

  1. Execute the following commands:
npx create-next-app@latest
cd my-app
npm install next-auth@beta
npx auth secret
npm install unstorage @auth/unstorage-adapter ioredis
  1. Create the following files:
import NextAuth from "next-auth"
import { UnstorageAdapter } from "@auth/unstorage-adapter"
import redisDriver from "unstorage/drivers/redis"
import { createStorage } from "unstorage"
 
const storage = createStorage({
  driver: redisDriver({
    host: 'localhost',
    tls: false as any,
    port: 6379
  }),
});
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: UnstorageAdapter(storage),
  providers: [],
})

./middleware.ts

export { auth as middleware } from "@/auth"

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

import { handlers } from "@/auth"
export const { GET, POST } = handlers
  1. Execute the app
npx next dev

Upvotes: 1

Views: 730

Answers (1)

Saad Bukhari
Saad Bukhari

Reputation: 11

can we use database functions using the edge runtime in nextjs? yes and no. you cannot directly use it but i have found out a solution to this, one method is to make an route handler (api). and using fetch in the edge runtime.

Possible Method for you usecase

in auth.js you can create separate auth.config.ts (which will not be using any kind of database operation that is not supported in the edge runtime github authjs5-nextjs

Upvotes: 1

Related Questions