Cannot find module './types'

Dear all, I have an error in my api project published in vercel, after the build.

The error says:
Cannot find module ‘./types’
Require stack:

  • /var/task/node_modules/@hapi/hoek/lib/clone.js
  • /var/task/node_modules/@hapi/hoek/lib/applyToDefaults.js
  • /var/task/node_modules/@hapi/hoek/lib/index.js
  • /var/task/node_modules/@hapi/boom/lib/index.js
  • /var/task/node_modules/@hapi/jwt/node_modules/@hapi/cryptiles/lib/index.js
  • /var/task/node_modules/@hapi/jwt/lib/crypto.js
  • /var/task/node_modules/@hapi/jwt/lib/index.js
  • /var/task/src/services/authService.js
  • /var/task/app.js
  • /var/task/___now_launcher.js
  • /var/runtime/index.mjs
    Did you forget to add it to “dependencies” in package.json?

However, on my machine it works perfectly.

On vercel, I even changed the run configuration. I overrided it to:
npm install --legacy-peer-deps

But it still doesn’t work.

Can someone please help me?

app.js:
//app.js
require(‘dotenv’).config();
const hapi = require(“@hapi/hapi”);
const { initializeApp, cert } = require(‘firebase-admin/app’);
const serviceAccount = require(‘./statsdatabase.json’);
const AuthService = require(‘./src/services/authService’); // Importa o serviço de autenticação

const init = async () => {
// Inicializa o Firebase Admin SDK
initializeApp({
credential: cert(serviceAccount),
storageBucket: ‘statsdatabase-b4489.appspot.com
});

// Configura o servidor Hapi
const server = hapi.server({
    port: process.env.PORT || 8080,
    host: "0.0.0.0",
    routes: {
        cors: true // Habilita CORS para permitir requisições de outros domínios
    },
    state: {
        strictHeader: false // Corrige problemas com cookies
    }
});

// Log global para todas as requisições
server.ext('onRequest', (request, h) => {
    console.log(`Received request for ${request.path} with method ${request.method}`);
    return h.continue;
});

// Log para verificar se a requisição chega ao manipulador (handler)
server.ext('onPreHandler', (request, h) => {
    console.log('onPreHandler: Requisição chegou ao manipulador');
    return h.continue;
});

// Middleware global para capturar erros
server.ext('onPreResponse', (request, h) => {
    const response = request.response;
    if (response.isBoom) {
        console.error('Global Error Handler:', response.output.payload);
    }
    return h.continue;
});

// Registra plugins, incluindo autenticação JWT e rate limiting
await server.register([
    require('@hapi/jwt'), // Autenticação JWT
    require('hapi-rate-limit') // Rate Limiting para proteger a API contra abusos
]);

// Configura a estratégia de autenticação JWT
server.auth.strategy('jwt', 'jwt', {
    keys: process.env.JWT_SECRET || 'your-secret-key', // Use uma variável de ambiente para a chave secreta
    verify: {
        aud: false,
        iss: false,
        sub: false,
        nbf: true,
        exp: true,
        maxAgeSec: 14400, // 4 horas
        timeSkewSec: 15
    },
    validate: AuthService.validateToken // Função para validar o token
});

// Carrega as rotas da aplicação
await server.register([
    require('./src/routes/homeRoutes'),
    require('./src/routes/teamRoutes'),
    require('./src/routes/tournamentRoutes'),
    require('./src/routes/newsRoutes'), // Inclui as rotas de notícias
    require('./src/routes/authRoutes') // Rota para autenticação
]);

console.log('Routes registered successfully');

// Inicia o servidor
await server.start();
console.log(`Server running at: ${server.info.uri}`);

};

// Inicia a aplicação
init().catch(err => {
console.error(err);
process.exit(1);
});

package.json:

{
“name”: “statsck-api”,
“version”: “1.0.0”,
“description”: “Stack API - Beta Version”,
“scripts”: {
“test”: “nyc mocha ‘tests/**/*.js’”,
“start”: “node app.js”
},
“author”: “Joás Ramos”,
“license”: “ISC”,
“dependencies”: {
@hapi/boom”: “^10.0.1”,
@hapi/hapi”: “^20.2.1”,
@hapi/hoek”: “^11.0.4”,
@hapi/jwt”: “^3.2.0”,
@hapi/vision”: “^7.0.3”,
“axios”: “^1.3.1”,
“bcrypt”: “^5.1.1”,
“dotenv”: “^16.4.5”,
“firebase-admin”: “^12.3.1”,
“got”: “^12.0.1”,
“hapi-rate-limit”: “^7.1.0”,
“multiparty”: “^4.2.3”,
“node-fetch”: “^3.2.0”,
“nodemailer”: “^6.9.14”,
“nodemon”: “^3.1.4”
},
“repository”: {
“type”: “git”,
“url”: “GitHub - sirjoasramos/statsck-api: Backend nodejs para consultar e persistir dados no Firebase Google Cloud
},
“devDependencies”: {
“chai”: “^4.3.7”,
“mocha”: “^10.2.0”,
“nyc”: “^15.1.0”,
“sinon”: “^15.2.0”
}
}

vercel.json:
{
“version”: 2,
“builds”: [
{
“src”: “app.js”,
“use”: “@now/node”
}
],
“routes”: [
{
“src”: “/(.)",
“dest”: “app.js”,
“methods”: [
“GET”,
“POST”,
“PUT”,
“DELETE”,
“PATCH”,
“OPTIONS”
],
“headers”: {
“Access-Control-Allow-Origin”: "

}
}
]
}

Hi @sirjoasramos. I suspect part of the problem is that your project uses the deprecated @now/node package. Please try updating to the @vercel/node package for the build configuration in vercel.json and let us know whether that works for you.

1 Like

thanks very much!
its work

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.