GraphQL gql Syntax Error: Expected Name, found }

98,415

Solution 1

I'm not 100% sure what the root of my problem was, but moving all the query code into a separate es6 module fixed the issue. There must have been some kind of contamination from the surrounding code. For reference my query was embedded within a React component.

This works:

import gql from 'graphql-tag'

const query = gql`
{
  user(id: 5) {
    firstName
    lastName
  }
}
`

export default query

Solution 2

This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.

Solution 3

The accepted answer didn't solve my issue. Instead, it worked if you remove the initial curly brackets.

The query should look like this instead:

const query=gql`
  user(id: 5) {
    firstName
    lastName
  }
`

Solution 4

The causes could be:

  • you are adding a "()" at the beginning for no reason
  • you need to add more 'nested' parameters.

Especially if you are using an online GraphiQL editor. Examples:

1- Wrong code (extra parenthesis)

{
  allFilms() {
    films {
      title
    }
  }
}

2- Wrong code (more parameters need it eg: title)

{
  allFilms {
    films {         
    }
  }
}

3- Correct code

{
  allFilms {
    films {
     title         
    }
  }
}

Solution 5

GraphQLError: Syntax Error: Expected Name, found "$".

One more example of a similar error (For other users).

theErrorIsHere (Could be extra ( or { before the $varName) added before $speakerId

Error code:

const FEATURED_SPEAKER = gql`
  mutation markFeatured($speakerId: ID!, $featured: Boolean!){
    markFeatured(speaker_id: theErrorIsHere$speakerId , featured: $featured){
      id
      featured
    }
  }
`;

Error output

Correct code:

const FEATURED_SPEAKER = gql`
  mutation markFeatured($speakerId: ID!, $featured: Boolean!){
    markFeatured(speaker_id: $speakerId , featured: $featured){
      id
      featured
    }
  }
`;
Share:
98,415
Nathan
Author by

Nathan

Updated on July 08, 2022

Comments

  • Nathan
    Nathan almost 2 years

    I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error:

    Syntax Error: Expected Name, found }

    This is generated by the following code:

    import gql from 'graphql-tag'
    
    const query = gql`
        {
          user(id: 5) {
            firstName
            lastName
          }
        }
      `
    
    console.log(query)
    

    I'm basing this code off the example code found here: https://github.com/apollographql/graphql-tag

    What is the Name referred to in the error message? Does anyone know what I'm doing wrong here?