3

I'm trying to implement user email verification in my pet project with GraphQL and Node.js.

I already have signUp resolver which sends verification token but I've just understood that when a user clicks a link there is no way to send data from an email to the next GraphQL resolver which would use the token and verify the email.

So the question is: shall I make REST endpoint /verify to do the work or there is a way to use /graphql endpoint

Andrew Korin
  • 294
  • 3
  • 17
  • If you have a GraphQL Server already up and running there is no need to implement REST endpoints. Just use GraphQL queries/mutations all the way. – Marco Daniel Apr 05 '19 at 11:13

1 Answers1

2

If you use a separate /verify endpoint, you'll most likely want to also redirect the user back to your site after processing the request. One approach would be to effectively reverse this flow, linking to your website and then having your page make the necessary GraphQL request.

Alternatively, you can invoke your verify resolver through a link in the email. express-graphql will handle both POST and GET requests. There's a couple of things to keep in mind with this approach though:

  • It will only work with queries, so your "verify" field will need to be on the Query type
  • The request will work in a browser context, but will flat out fail if you call it from inside, for example, GraphiQL

Here's a basic example:

const typeDefs = `
  type Query {
    verify: Boolean # Can be any nullable scalar
  }
`
const resolvers = {
  Query: {
    verify: (root, args, ctx) => {
      // Your verification logic
      ctx.res.redirect('https://www.google.com')
    }
  }
}
const schema = makeExecutableSchema({ typeDefs, resolvers })

app.use('/graphql', graphqlHTTP((req, res) => ({
  schema: MyGraphQLSchema,
  graphiql: false,
  // Inject the response object into the context
  context: { req, res },
})))

app.listen(4000)

You can then just navigate to this url in your browser:

http://localhost:4000/graphql?query={verify}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Hi Daniel this works however it gives the error "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client". I am using epress and graphql which redirects the browser to the respective location but throws that error on my express server – Graig Peru Jan 12 '20 at 18:34
  • is there a way i could prevent this ? – Graig Peru Jan 12 '20 at 18:36
  • There is not. Your GraphQL service really should not be used this way -- just use a separate endpoint. – Daniel Rearden Jan 12 '20 at 18:58