Hannes Z
Hannes Z

Reputation: 33

Prisma connection isn't working with Next.js middleware how can i solve this problem?

I want my Next.js website to only be accessible via login. However I get the following error:

Error [PrismaClientValidationError]: PrismaClient failed to initialize because it wasn't configured to run in this environment (Vercel Edge Functions or Edge Middleware).
In order to run Prisma Client in an edge runtime, you will need to configure one of the following options:
- Enable Driver Adapters: https://pris.ly/d/driver-adapters
- Enable Accelerate: https://pris.ly/d/accelerate

I use: Next.js: 14.2.4 @prisma/client: ^5.15.0 prisma: ^5.15.0 I am Using a SQLite Database

My folder structure is as follows

project-root/
│
├── /prisma
│   ├── schema.prisma
│   └──...
│
├── /src
│   ├── /app
│   │    ├── /(userFacing) 
│   │    │    └── ...
│   │    ├── layout.tsx
│   │    └── providers.tsx
│   ├── /components 
│   │    └── ...
│   ├── /lib 
│   │    └── isValidPassword.ts
│   ├── /db 
│   │    └── db.ts
│   └── middleware.ts
│
├── .env
├── .eslintrc.json
├── .gitignore
├── components.json
├── next-env.d.ts
├── next.config.mjs
├── package-lock.json
├── package.json
├── postcss.config.mjs
├── tailwind.config.ts
├── tsconfig.json

my middleware.ts

import { NextRequest, NextResponse } from "next/server";
import isValidPassword from "./lib/isValidPassword";

export default async function middleware(req: NextRequest) {
    if ((await isAuthenticated(req)) === false) {
        return new NextResponse("Unauthorized", {
            status: 401,
            headers: { "WWW-Authenticate": "Basic" },
        })
    }
}

async function isAuthenticated(req: NextRequest) {
    const authHeader = req.headers.get("Authorization") || req.headers.get("authorization");

    if (!authHeader || !authHeader.startsWith("Basic ")) {
        return false;
    }

    const base64Credentials = authHeader.split(" ")[1];
    const credentials = Buffer.from(base64Credentials, "base64").toString("utf-8");
    const [username, password] = credentials.split(":");

    const isValid = await isValidPassword(username, password);
    return isValid;
}



export const config = {
    matcher: "/"
};

my isValidPassword.ts

import bcrypt from "bcrypt";
import db from "../db/db"

export default async function isValidPassword(username: string, password: string) {

    try {

        const user = await db.user.findUnique({
            where: {
                username: username,
            },
        });

        if (!user) {
            console.log(`User '${username}' not found.`);
            return false;
        }

        const hashedPassword = await bcrypt.hash(password, 10)
        const isMatch = await bcrypt.compare(hashedPassword, user.password)

        return isMatch

    } catch (error) {
        console.error(`Error validating passwword ${error}`);
        return false;
    }
}

my db.ts

import { PrismaClient } from '@prisma/client'

const prismaClientSingleton = () => {
    return new PrismaClient()
}

declare global {
    var prisma: PrismaClient | undefined;
}

const db = global.prisma || prismaClientSingleton();

export default db

if (process.env.NODE_ENV !== 'production') {
    global.prisma = db;
}

my schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id       Int     @id @default(autoincrement())
  username String  @unique
  password String
  admin    Boolean @default(false)
}

Does anybody know what I'm doing wrong? I just can't find the error or the solution to it.

please help me. Many thanks in advance

Upvotes: 1

Views: 2412

Answers (2)

Adam Muse
Adam Muse

Reputation: 279

Did you try doing what it said in the error? Add the previewFeatures = ["driverAdapters"] to your prisma.schema

Upvotes: 0

CSD solutions
CSD solutions

Reputation: 1

Your middleware runs on the edge you need to use a prisma adapter like neon it supports edge runtime I recommend you look at this https://www.prisma.io/docs/orm/overview/databases/neon

Upvotes: 0

Related Questions