Search code examples
graphqlgraphql-fragments

Can you nest fragments in GraphQL?


Say you have fragment B, which depends on fragment A. I wonder whether you can plug-and-play fragment B in a query.


Solution

  • Yes, you can!

    Take these queries:

    fragment Bar on Foo {
      bar {
        id
      }
    }
    
    fragment Baz on Foo {
      baz {
        id
      }
    }
    
    
    fragment MetaFoo on Foo {
      id
      ...Bar
      ...Baz
    }
    
    query Qux {
      foo {
        ...MetaFoo
      }
    }
    

    Qux is a valid GraphQL query.