Deno HTTP Server not working on Deno Deploy with Oak

88 Views Asked by At

Hi I'm having trouble deploying my Deno server to Deno Deploy. I suppose it's having something to do with the Bcrypt library but I have no idea how I could fix this with maybe another library, or perhaps a deployment setting?

I'm using Oak as my middleware:

import { Application } from "https://deno.land/x/[email protected]/mod.ts";
import router from "./controllers/routes/routes.ts";

const app = new Application();
const PORT = 8080;

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Application is listening on port: ${PORT}`);

await app.listen({ port: PORT });

For example this code has a signin functionality. The API works fine, but whenever it comes to the Bcrypt it gives an error "ReferenceWorker - Worker is not defined" This is an example where I use the Bcrypt library:

import db from "./database/connectDB.ts";
import * as bcrypt from "https://deno.land/x/[email protected]/mod.ts";
import { pbkdf2 } from "https://deno.land/x/[email protected]/src/auth/pbkdf2.ts";
import { UserSchema } from "./schema/user.ts";
import { create, verify } from "https://deno.land/x/[email protected]/mod.ts";
import { key } from "./utils/apiKey.ts";
import { passwordTest, validateEmail } from "./utils/filters.ts";

const users = db.collection<UserSchema>("users");

export const signin = async ({ req, res }: { req: any; res: any }) => {
  const body = await req.body();
  const { username, password } = await body.value;

  if (!username || !password) {
    res.status = 400;
    res.body = {
      message: `Please provide all required fields: username and password.`,
    };
    return;
  }

  const user = await users.findOne({ username });
  if (!user) {
    res.status = 404;
    res.body = {
      message: `Invalid credentials`,
    };
    return;
  }

  const passwordMatch = await bcrypt.compare(password, user.password);
  if (!passwordMatch) {
    res.status = 401;
    res.body = {
      message: "Invalid credentials",
    };
    return;
  }

  const payload = {
    id: user._id,
    username: user.username,
  };
  const jwt = await create({ alg: "HS512", typ: "JWT" }, { payload }, key);
  
  if (jwt) {
    res.status = 200;
    res.body = {
      message: "User logged in",
      data: {
        _id: user._id,
        token: jwt,
        username: user.username,
      },
    };
  } else {
    res.status = 500;
    res.body = {
      message: "Internal server error",
    };
  }
};
1

There are 1 best solutions below

1
Ayo Reis On

Deno Deploy does not support the Web Workers API. Looking at bcrypt's documentation there are sync methods that don't use Web Workers.

Replacing bcrypt.compare with bcrypt.compareSync should work:

- const passwordMatch = await bcrypt.compare(password, user.password);
+ const passwordMatch = bcrypt.compareSync(password, user.password);