no "Perfomense" in sentry project on NestJs - nestjs

No data on the Performance tab in Sentry. The project is written in NestJS.
I connect Sentry like this
const app = await NestFactory.create(AppModule);
app.enableCors({
allowedHeaders: '*',
origin: '*',
methods: 'GET,PUT,POST,DELETE,OPTIONS',
preflightContinue: true,
});
const config = app.get<ConfigService>(ConfigService);
const dsnSentry = config.get('SENTRY_DSN');
Sentry.init({
dsn: dsnSentry,
environment: config.get('ENV'),
integrations: [
new Sentry.Integrations.Http({ tracing: true }),
],
tracesSampleRate: 1,
});
...
app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());
How do I get Performance in Sentry? Right now it's empty

As described in https://github.com/getsentry/sentry-javascript/issues/4731
some people had problems if this import was missing:
import "#sentry/tracing";

Related

how to fix "WebSocket connection to 'wss://apiURL/socket.io/?EIO=4&transport=websocket' failed: "

socket.io works fine on the localhost server, but after deploying it over https, I keep getting this error.
Client code:
export const socket = io.connect(process.env.REACT_APP_SERVER_URL, {
transports: ["websocket"],
// withCredentials: true,
cors: {
origin: [process.env.REACT_APP_SERVER_URL],
// origin: "*",
credentials: true,
},
});
Backend code:
const io = socketIO(server, {
cors: {
origin: [process.env.CLIENT_URL],
// origin: "*",
credentials: true,
},
});
When I type in the console.log "process.env.REACT_APP_SERVER_URL", the server API deployed by https comes in well, but I don't know what's wrong with socket communication.
As mentioned in the socket.io document, I tried using [credentials: true, withCredentials: true], and tried the same method as [origin: "*"] from Google, but all the same errors are coming out.
How can I solve it..?
Any help would be appreciated!

Why Axios request to a node(Express) back-end api still preflight OPTIONS request even if http-proxy-middleware is configured?

I'm trying to figure out why when I make a call to my "API" (nodejs express) from my React client the OPTIONS, preflight request is executed first.
Server api run on http://localhost:8000
Client run on http://localhost:3000
In my React client I configured http-proxy-middleware as follows:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
Also the Axios instance is created with following options
const options = {
baseURL: BASE_URL,
timeout: 300000,
withCredentials: false,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
};
axios.create(config);
The Node.js(Express) BackEnd application is configured as follow:
app.use(cors(
{
"origin": "*", // just for test...
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": "*" // just for test
}
));
When I make a Post for instance for server-side token validation a preflight OPTIONS request is made. How can I avoid this ? Am I doing something wrong?
Thank you all.

Cors problem with nestjs in centos 7 local machine

Hi I have a FE react app and a BE nest.js app running on the same centos 7 virtual machine, my problem is that I can't make the rest calls from FE to BE due to the error reported under the thing that seems to me strange is that on my local machine, ubuntu there is no cors error, what is this due to? how can i fix it? i have to edit axios
Error:
Multi-origin request blocked (cross-origin): the origin match criterion does not allow the remote resource to be read from http: // localhost: 3001 / user. Reason: CORS request failed. Status code: (null)
Nest.js code:
import { ValidationPipe } from "#nestjs/common";
import { NestFactory } from "#nestjs/core";
import { SwaggerModule, DocumentBuilder } from "#nestjs/swagger";
import { AppModule } from "./app.module";
import * as cookieParser from "cookie-parser";
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: true,
});
const config = new DocumentBuilder()
.setTitle("Backend ")
.setDescription("Api Backend")
.setVersion("1.0")
.addTag("Backend")
.addBearerAuth(
{ type: "http", scheme: "bearer", bearerFormat: "JWT" },
"access-token"
)
.build();
//Setup swagger module
var options = {
deepScanRoutes: true,
};
const document = SwaggerModule.createDocument(app, config, options);
SwaggerModule.setup("api", app, document);
app.useGlobalPipes(new ValidationPipe());
app.use(cookieParser());
//Enable cors
app.enableCors({
origin: ["http://localhost:3001","http://localhost:3006", "http://80.211.128.77:3001","http://memoryp.org:3006"],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
});
await app.listen(3001);
}
bootstrap();

Cors Origin specified, but wildcard is sent as response - NodeJS Express Cors()

I have a simple but annoying issue. I am running a nodejs server with Apollo Server for GraphQL and express for handling the web requests. I am setting a cookie after a successful login in redis via express-session
I do set the origin and the credentials options for cors()
However, on the front-end I still get the error message, that there is a wildcard in use.
If I changed the origin to "http://localhost:3000/" it would throw me the message, that it is not included in the origin list.
The cookie gets set:
The response also gives me:
When setting the credentials of createHTTPLink to same-origin no cookie is set. as per documentation (https://www.apollographql.com/docs/react/networking/authentication/)
You just need to pass the credentials option. e.g. credentials: 'same-origin' as shown below, if your backend server is the same domain or else credentials: 'include' if your backend is a different domain.
Error Message:
Access to fetch at 'http://localhost:4000/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Node JS index.ts
import "reflect-metadata";
import dotenv from "dotenv";
import { ApolloServer } from "apollo-server-express";
import Express from "express";
import { buildSchema } from "type-graphql";
import session from "express-session";
import connectRedis from "connect-redis";
import {redis} from "./services/redis"
import cors from "cors"
import { createConnection } from "typeorm";
// load .env file
dotenv.config()
const main = async () => {
await createConnection({
name: "default",
type: "postgres",
host: "localhost",
port: 5432,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
synchronize: true,
logging: true,
entities: [__dirname + "/modules/*/*.*"],
});
// build the graphQL schema
// load all the resolvers!
const schema = await buildSchema({
resolvers: [__dirname + "/modules/**/!(*.test).ts"],
});
// create the apollo server with the schema and make sure we have access
// to req and res in context!
const apolloServer = new ApolloServer({
schema,
context: ({req, res} : any) => ({req, res})
});
// initialise Express itself
const app = Express();
// add the cors for the react frontend
app.use(cors({
credentials: true,
origin: "http://localhost:3000"
}))
// create the redis connection
const RedisStore = connectRedis(session)
// setup the redis session
const redisSessionStore = session({
store: new RedisStore({
client: redis as any,
}),
name: process.env.COOKIE_NAME,
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 1000 * 60 * 60 * 24 * 1 * 365, // 1 year
},
} as any)
// make sure redis is used before we mix with apollo
app.use(redisSessionStore);
apolloServer.applyMiddleware({ app });
// start the server
app.listen(process.env.PORT, () => {
console.log(`Started on http://localhost:${process.env.PORT}/graphql`);
});
};
main();
React JS Front-End
import { ApolloClient, createHttpLink, InMemoryCache } from "#apollo/client";
const link = createHttpLink({
uri: "http://localhost:4000/graphql",
credentials: 'include'
})
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
export default client;
The solution to this problem is to actually set the corsOptions on the Apollo Server configuration.
apolloServer.applyMiddleware({ app, cors: corsOptions });

nodejs + express: Cors is not a function

Been working fine up until this morning and now, suddenly i am getting a type error stating that Cors is not a function
My code
import * as Cors from "cors";
...
const corsOptions: Cors.CorsOptions = {
allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept", "X-Access-Token", "Authorization"],
credentials: true,
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
origin: "*",
preflightContinue: true
};
createConnection(ormConfig).then(async connection => {
// run pending migrations
await connection.runMigrations();
// create express server
const app = express();
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true}));
// register cors
app.use(Cors(corsOptions)); //<---error occurs here
// register all controllers
useExpressServer(app, {
routePrefix: "/api",
controllers: [
__dirname + "/controllers/**/*{.js,.ts}"
],
authorizationChecker: async (action: any, roles: string[]) => {
return JwtAuthorizationMiddleware.checkIsAuthorized(action, roles);
},
currentUserChecker: async (actions: any) => {
return JwtAuthorizationMiddleware.extractUserFromJwtToken(actions);
}
});
// start the express server
const port: number = +(process.env.PORT || 44320);
app.listen(port, (err: Error) => {
console.log(`App listening on port ${port}`);
console.log("Press Ctrl+C to quit.");
});
}).catch(error => console.error("TypeORM connection error: ", error));
Current versions of cors and Node
cors: "^2.8.4"
Node: v8.4.0
The only change that recently done was on Friday when I included the following packages
multer: "^1.3.0"
#google-cloud/datastore: "^1.1.0"
#google-cloud/storage: "^1.4.0"
and everything was working till this morning, same version is deployed on gcloud and this works so I am a little bemused as to why I Am suddenly getting this error and what could be the cause.
Any help is greatly appreciated
You have to have something such as
const cors = require('cors');
in the top of your file, and then refer to the module as cors, not Cors.
You can read Express's cors documentation to learn more.
To apply cors to all routes in your project you can write:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Ok, so I found the problem which turned out to be PEBKAC.
While implementing file uploads and storage in gcloud, I had to enable CORS on gcloud and had saved the settings file in the root of my project, this file was called cors.json.
In the code posted in my question above the import statement was reading my cors.json file and not (as I thought) the cors NPM package.
Lesson learnt from this one should anyone else make the same rookie mistake I just made is be careful what you name your files and where you put them!!!

Resources