How to use custom express middleware within Nuxt.js

Viewed 834

I am building an app using Nuxt.js. One of the things that drew me to Nuxt specifically, was it's implementation of serverMiddleware.

The app is a cookbook so I can automate meal planning at my house :)

I have the Nuxt app set up with the following middleware

nuxt.config.js

serverMiddleware: [{ path: '/api', handler: '~server/main.ts' }],

main.ts

import 'dotenv/config';
import express, {
    Request,
    Response,
    NextFunction
} from 'express';
import mongoose from 'mongoose';
import routesv1 from './api/endpoints/v1/routes';
import dayjs from 'dayjs';

const server = express();

const dbUri: string = `mongodb+srv://${process.env.mongoUser}:${process.env.mongoPassword}@dev.ivzgx.mongodb.net/dev`;

mongoose.connect(dbUri, { ssl: true, sslValidate: false})
    .then(() => {
        console.log(`[${dayjs()}] Connected to MongoDB`);
    }).catch(error => {
        console.warn(error);
    });
server.use(express.urlencoded({ extended: false }))
server.use((req: Request, res: Response, next: NextFunction) => {
    console.info(`[${req.method}] ${req.url} ${res.statusCode}`);
    next();
    });

server.use(express.json());
server.use('/v1', routesv1);

export default server

When I run nom run dev I see that mongoose has connected, and the server runs properly.

Additionally, I have set up a test route

server/api/endpoints/v1/routes.ts

import express, {Request, Response, Express} from 'express';
import validateResource from '../../middleware/validateResource';
import { createRecipeSchema } from '../../schema/recipe.schema';
import { createRecipeHandler } from '../../controller/recipe.controller'

const router = express.Router();

router.get('/test', (req: Request, res: Response) => {
    res.send('test endpoint');
})

router.post('/recipe', async (req: Request, res: Response) => {
    console.log("router hit; passing to validation middleware")
    validateResource(createRecipeSchema),
    createRecipeHandler
})

export default router

Now this is where I am lost...

I am able to hit the test route without any issues; I receive the 200 status, and I receive the 'test endpoint' message.

When I attempt to post data to the recipe endpoint, the console prints that the request was received at the route and is being passed to the following middleware

server/api/middleware/validateResource.ts

import { Request, Response, NextFunction } from "express";
import { AnyZodObject } from "zod";

const validate = 
    (schema: AnyZodObject) => 
    (req: Request, res: Response, next: NextFunction) => {
        try {
            console.log('attempting to parse schema')

            schema.parse({
                body: req.body,
                query: req.query,
                params: req.params
            });
            next();
        } catch (e: any) {
            return res.status(400).send(e.errors);
        }
    };

export default validate;

but the request just hangs and is never passed to the custom middleware...

Is the middleware improperly configured? Does Nuxt not like using additional middleware with express? Please help

0 Answers
Related