Home > Mobile >  Use adapter-node (SvelteKit) to create middleware for Express server
Use adapter-node (SvelteKit) to create middleware for Express server

Time:12-21

I'm attempting to implement a SvelteKit front-end onto my existing Express server, that handles auth and such.

I'm using the node adapter and trying to connect it to my Express app as middleware, with

app.use(assetsMiddleware, prerenderedMiddleware, kitMiddleware);

and importing from

const { assetsMiddleware, prerenderedMiddleware, kitMiddleware } = "./client/build/middlewares.js";

but I get the error

TypeError: Router.use() requires a middleware function but got a undefined

which leads me to believe it's not importing the modules correctly and the three imports are all undefined, though I can see in the middlewares.js file the exports are correct. I tried ES6 modules but no success with that, plus I prefer to stick to commonJS with Express. I can't find any repos or tutorials on using the node adapter this way, and the docs are sparce.

Essentially, what is the fix for this error? I would also appreciate any resources that may help get SK as middleware in Express working!

CodePudding user response:

It appears that you have forgotten to require() "./client/build/middlewares.js";. Object destructure a string (ie const { x, y } = "Some String") makes the variables undefined. So to app.use() your actually passing three variables that equal undefined (ie assetsMiddleware === undefined). Thats why it gives a TypeError.

So the change you need to make is this:

const { assetsMiddleware, prerenderedMiddleware, kitMiddleware } = require("./client/build/middlewares.js");

I hope this fixes it for you!

  • Related