Plug Nested Router - How to Acesss Parent Glob?

I’ve got my plug routes separated such that I forward subroutes to different file:

In users.ex

forward "/:user_id/playlists", to: Api.Users.Playlists

From playlists.ex

get "/" do
  user_id # <--- ???
end

How can I access the :user_id glob from playlists.ex?

1 Like

You do not access it in the router, you access it as an argument in the map given to function callbacks. You will have a key of “user_id” with that value. :slight_smile:

What map and function callbacks are you referring to?

Globs are accessed in route handlers: https://hexdocs.pm/plug/Plug.Router.html#module-routes

How can I access the glob when it’s defined from a parent router (forward macro)?

In the get "/" do function, try running IO.inspect conn and see what information it provides.

3 Likes

There is a property script_name inside conn which contains the path parts which I can use to get my user_id

script_name: ["users", "123", "playlists"]

However, I think this is a pretty common problem and a common solution by Plug should exist.

1 Like

However, I think this is a pretty common problem and a common solution by Plug should exist.

:script_name is exactly the solution you are looking for. :blush: It is there for exactly this use case!

3 Likes