Search code examples
node.jsamazon-web-servicesexpressrequestaws-xray

AWS X-Ray with Node.JS Express and request


So I'm trying to implement X-Ray with my express app. I have my app.js file and inside reference a router file.

my project structure:
project/ routes/ index.js app.js

app.js:

var indexRouter = require("./routes/index")
...
app.use("/", indexRouter)
...

index.js:

const AWSXRay = require("aws-xray-sdk")
const request = require("request")

router.post("/xray", async function(req, res, next) {
    let app = req.app
    app.use(AWSXRay.express.openSegment("MyApp"))

    try {
        console.log(AWSXRay.getSegment()) // this succesfully gets segment
        AWSXRay.captureAsyncFunc("send", function(subsegment) {
            request.get("http://www.google.com", { XRaySegment: subsegment }, function() {
                res.json({
                    success: "success"
                })
                subsegment.close()
        })
    } catch (err) {
        next(err)
    }
    app.use(AWSXRay.express.closeSegment())
})

I'm following the automatic mode examples: Capture through async function calls from the AWS documentation (https://docs.aws.amazon.com/xray-sdk-for-nodejs/latest/reference/index.html), but I am getting a error that says: "Failed to get the current sub/segment from the context."


Can anyone let me know what I am doing wrong?


Solution

  • You should move the app.use(AWSXRay.express.openSegment("MyApp")) code to the app.js above the app.use("/", indexRouter)

    Then move the app.use(AWSXRay.express.closeSegment()) below the app.use("/", indexRouter).

    If you look at the code referenced in the link provided, you'll notice the openSegment and closeSegment are outside the route, not inside (as you have them currently)

    Code in link for reference:

    var app = express();
    
    //...
    
    var AWSXRay = require('aws-xray-sdk');
    
    app.use(AWSXRay.express.openSegment('defaultName'));               //required at the start of your routes
    
    app.get('/', function (req, res) {
      res.render('index');
    });
    
    app.use(AWSXRay.express.closeSegment());   //Required at the end of your routes / first in error handling routes