Search code examples
strapi

How to get a URL parameter in Strapi?


The route in question is something like this: chats/5de3e056c022b2b3252dab43/messages but I cant seem to find a relatively straightforward way to retrieve the ID (5de3e056c022b2b3252dab43) and its nowhere to be found (yes I can parse the url but I was hoping there is a better way - something along the lines of req.params.id)

Basically this is what the CTX object looks like:

{
    "request": {
        "method": "GET",
        "url": "/chats/5de3e056c022b2b3252dab43/messages",
        "header": {
            "authorization": "Bearer ******",
            "user-agent": "PostmanRuntime/7.19.0",
            "accept": "*/*",
            "cache-control": "no-cache",
            "postman-token": "e320fdc2-81a5-4f36-a4d1-ec621188e27d",
            "host": "localhost:1337",
            "accept-encoding": "gzip, deflate",
            "connection": "keep-alive"
        }
    },
    "response": {
        "status": 200,
        "message": "OK",
        "header": {
            "vary": "Origin",
            "content-security-policy": "img-src 'self' http:; block-all-mixed-content",
            "strict-transport-security": "max-age=31536000; includeSubDomains",
            "x-frame-options": "SAMEORIGIN",
            "x-xss-protection": "1; mode=block",
            "content-type": "application/json; charset=utf-8",
            "x-powered-by": "Strapi <strapi.io>"
        }
    },
    "app": {
        "subdomainOffset": 2,
        "proxy": false,
        "env": "development"
    },
    "originalUrl": "/chats/5de3e056c022b2b3252dab43/messages",
    "req": "<original node req>",
    "res": "<original node res>",
    "socket": "<original node socket>"
}

Solution

  • If you have a custom route like this /chats/:id/messages

    In your controller, you will be able to access to the ID of the chat by using ctx.params.id