简体   繁体   中英

How to verify user email while using GraphQl and Node.js

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

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM