Fastify crashing on route registration

14 Views Asked by At

Why the Fastify app is crashing when I register a route file?

app.register( import( "./Routes/UserRoutes.js" ), { prefix: '/user' } )

UserRoutes.js

export async function userRoutes( fastify ) {
    fastify.get( '/fast', function ( request, reply ) {
        reply.code( 200 ).send( { hello: 'world' } )
    } )
}

The error

    2024-02-22 23:19:58 ERROR: Cannot read properties of undefined (reading 'name')
2024-02-22 23:19:58     err: {
2024-02-22 23:19:58       "type": "TypeError",
2024-02-22 23:19:58       "message": "Cannot read properties of undefined (reading 'name')",
2024-02-22 23:19:58       "stack":
2024-02-22 23:19:58           TypeError: Cannot read properties of undefined (reading 'name')
2024-02-22 23:19:58               at Object.checkPluginHealthiness (/opt/project/node_modules/fastify/lib/pluginUtils.js:140:22)
2024-02-22 23:19:58               at Object.registerPlugin (/opt/project/node_modules/fastify/lib/pluginUtils.js:147:26)
2024-02-22 23:19:58               at Boot.override (/opt/project/node_modules/fastify/lib/pluginOverride.js:28:57)
2024-02-22 23:19:58               at Boot._loadPlugin (/opt/project/node_modules/avvio/boot.js:416:25)
2024-02-22 23:19:58               at /opt/project/node_modules/avvio/boot.js:395:12
2024-02-22 23:19:58               at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
2024-02-22 23:19:58     }
2024-02-22 23:19:58 [nodemon] app crashed - waiting for file changes before starting...

I can't trace the error because I don't have name property.

1

There are 1 best solutions below

0
Marvix On

My bad, I missed reading the docs, the route file should be like this:

export default async function userRoutes( fastify, opts, done ) {
    fastify.get( '/fast', function ( request, reply ) {
        reply.code( 200 ).send( { hello: 'world' } )
    } )
    done()
}

The function should end with done().

For reference: https://fastify.dev/docs/latest/Reference/Routes/