Search code examples
node.jsexpressamazon-elastic-beanstalkswagger-uiaws-codepipeline

Cors issues on Nodejs express api swagger-ui-express API documentation hosted on aws beanstalk


I have Nodejs express app that is deployed on AWS elastic beanstalk. I can access the APIS without any problem but when I try to access swagger API docs, I get cors errors, and the page loads forever until it shows nothing.

I am handling cors in the application already using the cors npm package but it is not helping.

Does anyone have an idea about how I can solve this? I would be happy to provide more details for anyone who wants to help.

Thanks.

enter image description here

import router from '@api';
import * as statusCodes from '@constants/statusCode';
import { dbConnect } from '@dbConfig';
import swaggerDocument from '@swaggerDocs';
import { errors } from 'celebrate';
import compression from 'compression';
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import helmet from 'helmet';
import createError from 'http-errors';
import logger from 'morgan';
import swaggerUi from 'swagger-ui-express';

dotenv.config();
dbConnect();

const app = express();
app.use(cors());
app.use(helmet());
app.use(compression());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use('/api/v1', router);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

// catch 404 errors
app.use((_, _1, next) => {
    next(createError(statusCodes.HTTP_NOT_FOUND));
});

app.use((err, req, res, next) => {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || statusCodes.HTTP_SERVER_ERROR);
    const response = { message: err.message, error: err.status };
    res.send(response);
    next();
});

app.use(errors());

export default app;


Solution

  • After setting up SSL and adding a domain to the application, I was able to load swagger UI documentation. Maybe this might help someone in the future, but I wish I knew how to do it before adding a domain.