开发者

Server code in *.server.ts getting bundled in Remix JS Client

I am building a Remix JS / Prisma app, following the Remix Jokes App tutorial by Kent C Dodds.

I am getting an error that says:

PrismaClient is unable to be run in the browser.

even though PrismaClient is being run inside a *.server.ts file which means the Remix compiler should be excluding it from the client bundle.

Here is my route file:

// app/routes/auth/login.tsx

import {
  type ActionFunction,
  json
} from "@remix-run/cloudflare";
import LoginScreen from "~/screens/LoginScreen"
import { login } from "~/utils/session.server"; // Import from .server file
import { useActionData } from "@remix-run/react";


const badRequest = (data: ActionData) =>
  json(data, { status: 400 });

export const action: ActionFunction = async ({
  request,
}) => {
  // Get and validate input [Omitted]

  const user = await login({ email, password }); // <-- Problematic code path
  if (!user) {
   return badRequest({
     fields,
     formError: `Incorrect username or password.`,
   });
  }
  // Redirect user into the app [Omitted]
}

export const loader = () => null;

export default function LoginRoute() {
  const data = useActionData();
  return (
    <LoginScreen formError={data?.formError} fieldErrors={data?.fieldErrors}/>
  )
}

Here is my session.server.ts file, where I define the login function:

// app/utils/session.server.ts

import bcrypt from "bcryptjs";
import { db } from "./db.server";

export async function login({
  email,
  password,
}) {
  const user = await db.user.findUnique({ where: { email } }); // <-- Problematic code path

  if (!user) return null;
  const isCorrectPassword = await bcrypt.compare(
    password,
    user.passwo开发者_开发技巧rdHash
  );
  if (!isCorrectPassword) return null;
  return { id: user.id, email };
}

Here is where I defined PrimsaClient:

// app/utils/db.server.ts

import { PrismaClient } from "@prisma/client";

let db: PrismaClient;

declare global {
  var __db: PrismaClient | undefined;
}

// This is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
if (process.env.NODE_ENV === "production") {
  db = new PrismaClient();
} else {
  if (!global.__db) {
    global.__db = new PrismaClient(); <-- This is where the exception is happening
  }
  db = global.__db;
}

export { db };

Why is Primsa being run in the client given that it's inside *.server.ts?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜