How can I match the root without overriding all other paths in Phoenix Router?

I’m trying to route all requests to “/” to absinthe for graphql resolution. The problem is that when I forward “/” to absinthe, no other route will work. If I visit any other route, even if the route doesn’t exist, I get an error of {"errors":[{"message":"No query document supplied"}]}. What is going on? How can I accept graphql requests under / while still being able to access /mailbox, /graphiql, and dashboard?

defmodule HydroapiWeb.Router do
  use HydroapiWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/" do
    pipe_through :api

    forward "/", Absinthe.Plug, schema: HydroapiWeb.Schema
    forward "/mailbox", Plug.Swoosh.MailboxPreview
  end

  if Mix.env() in [:dev, :test] do
    import Phoenix.LiveDashboard.Router

    scope "/" do
      pipe_through [:fetch_session, :protect_from_forgery]

      live_dashboard "/dashboard", metrics: HydroapiWeb.Telemetry
    end
  end

Liam,

Put the forward "/", Absinthe.Plug, schema: HydroapiWeb.Schema call as the last in the router. Having it first means it catches everything.

defmodule HydroapiWeb.Router do
  use HydroapiWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  if Mix.env() in [:dev, :test] do
    import Phoenix.LiveDashboard.Router

    scope "/" do
      pipe_through [:fetch_session, :protect_from_forgery]

      live_dashboard "/dashboard", metrics: HydroapiWeb.Telemetry
    end
  end

  scope "/" do
    pipe_through :api

    forward "/mailbox", Plug.Swoosh.MailboxPreview
    forward "/", Absinthe.Plug, schema: HydroapiWeb.Schema
  end
end
1 Like

Hey thanks Adam. I’m new to elixir. I imagine this behaviour exists because the calls to forward are essentially plug middlewares appearing in the chain. What is happening inside of the forward "/" line that allows it to act as a wildcard?

1 Like

forward literally is a wildcard, that is its purpose. It forwards any request beginning with that prefix to that middleware

Tangentially, I don’t really recommend having your root path serve GraphQL, it’d make a lot more sense as /api or /graphql.

4 Likes