Next.js Discord

Discord Forum

How to use node modules in app router's api routes?

Answered
Chum salmon posted this in #help-forum
Open in Discord
Chum salmonOP
I am not trying to use native node modules in app router's api route.
Answered by Jboncz
I cant get that library working.
View full answer

71 Replies

Chum salmonOP
@Jboncz
Hi
So share with me some code and let me see whats going on
Chum salmonOP
import { NextResponse } from 'next/server';
import { hash } from 'node:crypto';

export async function POST(req: Request, res: Response) {
  const { address } = await req.json();

  console.log(hash('blake2', Buffer.from(address)));
  console.log({ address });
  return NextResponse.json({
    tx: address.toString(),
  });
}
and what error are you getting?
Chum salmonOP
 TypeError: (0 , node_crypto__WEBPACK_IMPORTED_MODULE_1__.hash) is not a function
    at POST (webpack-internal:///(rsc)/./app/api/v0/bounties/test/route.ts:12:66)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /home/hypo/Workspace/novalab/Raiders.dev/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:63809
Are you using the app router or pages router?
Looks like pages
Chum salmonOP
App router
Oh your right sorry
My bad
import { NextResponse } from 'next/server';
import { createHash } from 'crypto';

export async function POST(req: Request, res: Response) {
  try {
    const { address } = await req.json();

    // Use the Blake2b algorithm for hashing
    const hash = createHash('blake2b').update(address).digest('hex');

    console.log('Hash:', hash);
    console.log('Address:', address);

    return NextResponse.json({
      hash,
      address,
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json({
      error: 'An error occurred while processing the request',
    }, { status: 500 });
  }
}


try this.
Chum salmonOP
Looks like when I try to use node native module, I get this.
Yeah hash isnt a function
TypeError: (0 , node_crypto__WEBPACK_IMPORTED_MODULE_1__.hash) is not a function

This error is indicating your trying to import something that doesnt exsist.
If you look at that link you will see how its suppose to be used πŸ™‚
Chum salmonOP
Oh, yeah, I see.
That was what I am trying to explain as example
What I want to use is blake2 module
Which gives me this error
sooo it would be something like
import {createHash} from 'blake2'
your intellisense shoudl auto complete it
Chum salmonOP
import { NextResponse } from 'next/server';
import { createHash } from 'blake2';

export async function POST(req: Request, res: Response) {
  try {
    const { address } = await req.json();

    // Use the Blake2b algorithm for hashing
    const name = createHash('blake2b', { digestLength: 32 })
      .update(Buffer.from(address, 'utf8'))
      .digest('hex');

    return NextResponse.json({
      name,
      address,
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      {
        error: 'An error occurred while processing the request',
      },
      { status: 500 }
    );
  }
}
This is my code.
And I get that error
Lemme look at this library. Unfortuantely ive never used it
Chum salmonOP
😭
May I use odd one
πŸ™
Ive never even heard of blake2, I just use sha256
99% of the time
Chum salmonOP
blak2 is what is used in blockchain network
called Cardano
ahhh
import blake2 from 'blake2';

const h = blake2.createHash('blake2b');


try doing it like this.
instead of destructuring
    import blake2 from 'blake2';

    const name = blake2.createHash('blake2b', { digestLength: 32 })
      .update(Buffer.from(address, 'utf8'))
      .digest('hex');
Chum salmonOP
Same 😭
can you paste the error in here?
Chum salmonOP
Module not found: Can't resolve './build/Release/blake2'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./app/api/v0/bounties/test/route.ts
can you show me your package.json?
Chum salmonOP
{
  "name": "boonties",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev -p 4000",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@formkit/auto-animate": "^0.8.1",
    "@react-hook/window-size": "^3.1.1",
    "@stitches/react": "^1.2.8",
    "@types/blake2": "^4.0.4",
    "app-root-path": "^3.1.0",
    "aws4": "^1.12.0",
    "axios": "^1.7.2",
    "blake2": "^5.0.0",
    "blakejs": "^1.2.1",
    "easy-peasy": "^6.0.4",
    "lucid-cardano": "^0.10.7",
    "moment": "^2.30.1",
    "mongoose": "^8.1.1",
    "next": "14.1.0",
    "next-auth": "^4.24.7",
    "novalab-raiders": "^0.0.4",
    "react": "^18",
    "react-dom": "^18",
    "react-toastify": "^10.0.4",
    "tailwind-scrollbar": "^3.1.0",
    "twitter-api-v2": "^1.17.2",
    "zod": "^3.22.4"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.1.0",
    "postcss": "^8",
    "tailwindcss": "^3.3.0",
    "typescript": "^5"
  }
}
alright let me spin up a project and take a look one sec.
Chum salmonOP
Thank you sir
bah, need python installed lol
sec, gottta spin up vm, dont wanna bork my system lol
Are you doing this on windows or linux? Just curious
Chum salmonOP
linux
ahhh okay, would be easier probably lol
Funny your the first person in the history of this server to ever post anything with the word 'blake2' in it.
πŸ˜…
Chum salmonOP
πŸ˜…
Its still installing, had to install visual studio for the C++ environment stuff
Chum salmonOP
Seems it designed for web brower
πŸ˜…
Im just going to help you with your issue xD I dont wanna get to far into the weeds I just got the module installed
Chum salmonOP
Thank you for your support
You are πŸ‘
I cant get that library working.
Answer
Id recommend using

import { blake2b } from '@noble/hashes/blake2b';
import { blake2b } from '@noble/hashes/blake2b';


export async function callBlake(address) {
    const b2params = { key: new Uint8Array([1]), dkLen: 32 };
    const h10c = blake2b.create(b2params).update(Uint8Array.from([1, 2, 3])).digest();

    console.log(h10c)

    return h10c;
}


Somewhat of a basic example I got working in my environment
Chum salmonOP
Awesome
It is really a 0 dependency library
πŸ‘
Make sure to mark an answer if it solved the issue πŸ™‚