• Stars
    star
    203
  • Rank 192,890 (Top 4 %)
  • Language
    JavaScript
  • Created almost 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Authentication Boilerplate with Next.js and Apollo GraphQL

Auth Example with Next.js and Apollo

This example shows how to implement Authentication with Next.js and Apollo GraphQL.

Main Technologies Used

  • Apollo GraphQl
  • Express.js
  • Express Validator
  • Next.js
  • Passport.js
  • Passport-local-mongoose
  • Passport-github

Contents

Project Structure

├── components
│   └── forms
│   ├── login.js
│   └── signup.js
├── lib
│   ├── initApollo.js
│   └── withData.js
├── pages
│   ├── index.js
│   ├── login.js
│   └── signup.js
└── server
├── data
│   ├── resolvers.js
│   └── schema.js
├── models
│   └── User.js
├── services
│   └── passport.js
└── index.js

Mutations

Schema

Here we have one User's type with three fields (email, fullname and password), one Query type with a profile field just to keep GraphQL's mouth shut about having a Query type defined. We have two Mutation types (login, and signup).

type User {
	email: String
	fullname: String
	password: String
}

type Query {
	profile: User
}

type Mutation {
	createUser(email: String!, fullname: String, password: String!): User
	login(email: String!, password: String!): User
}

Resolvers

The resolvers we care about here are createUser and login. They both take in email and password as arguments with createUser taking an extra fullname argument.

Mutation: {
		createUser(root, { email, fullname, password }, { login }) {
			const user = new User({ email, fullname })

			return new Promise((resolve, reject) => {
				return User.register(user, password, err => {
					if (err) {
						reject(err)
					} else {
						login(user, () => resolve(user))
					}
				})
			})
		},
		login(root, { email, password }, { login }) {
			return new Promise((resolve, reject) => {
				return User.authenticate()(email, password, (err, user) => {
					// user returns false if username / email incorrect
					if (user) {
						login(user, () => resolve(user))
					} else {
						reject('Email / Password Incorrect')
					}
				})
			})
		}
	}

Models

Oops! We have only one model (User). It accepts email, validates the email with express-validator. Then we have a plugin to tell passport-local-mongoose to use our email field as the default usernameField.

const userSchema = new Schema({
	email: {
		type: String,
		unique: true,
		lowercase: true,
		trim: true,
		validate: {
			isAsync: true,
			validator: (v, cb) =>
				cb(validator.isEmail(v), `${v} is not a valid email address`)
		},
		required: 'Please Supply an email address'
	},
	fullname: String
})

userSchema.plugin(passportLocalMongoose, {
	usernameField: 'email',
	errorMessages: {
		UserExistsError: 'Email Already Exists'
	}
})

Deploy

Deploy to now

License

MIT

More Repositories

1

NextSimpleStarter

🐳 Simple and Accessible PWA boilerplate with Nextjs 12 and MUI
JavaScript
938
star
2

vuex-examples

🐻 Simple Examples on using Vuex to build Real World Apps
JavaScript
258
star
3

react-rough

🐇 React Components for Rough.js
TypeScript
177
star
4

react-click-away-listener

🐾 Tiny React Click Away Listener built with React Hooks
TypeScript
174
star
5

awesome-apollo-graphql

A curated list of amazingly awesome things regarding Apollo GraphQL ecosystem 🌟
149
star
6

use-fetch-hook

A custom hook to fetch and cache data
JavaScript
113
star
7

pimg

📷 Mini Image Lazy Loader for P(R)eact and Vue
JavaScript
99
star
8

PreactSimpleStarter

PWA Simple Starter with Preact, Preact-mdl and Webpack2 🔥🔥🔥
JavaScript
64
star
9

Advanced-JavaScript

Documentation based on John Resig's website on Advanced JavaScript
JavaScript
55
star
10

array-explorer-cli

⚡ A CLI package to help figure out what JavaScript array method would be best to use at any given time
JavaScript
47
star
11

yooda

🧘‍♂️600b validation library with support for custom handlers and messages.
TypeScript
33
star
12

object-explorer-cli

⚡ A CLI package to help figure out what JavaScript object method would be best to use at any given time
JavaScript
17
star
13

state-machines-workshop

Unstack Conf workshop on State machines and State charts
JavaScript
15
star
14

next-react-toolbox

React Toolbox integration with Next.js 📦
JavaScript
12
star
15

ApolloSimpleStarter

🌟 Bare Minimum implementation of Apollo Server & Client with MERN
JavaScript
11
star
16

ng-states

~400 Bytes Nigeria State list with its respective Local Government Areas
JavaScript
10
star
17

react-library-starter

A simple boilerplate to help get started in creating production ready react libraries
JavaScript
9
star
18

cors

Bypass CORS
JavaScript
8
star
19

global-context-example

Using Contexts to properly manage global states
JavaScript
8
star
20

PreactStatic

Working out SSR with Preact
JavaScript
8
star
21

always-treeshake-mui

An example on how to properly tree-shake mui with next.js
JavaScript
8
star
22

css2object

Converts css to object/json (fun thang!) 🤔
TypeScript
8
star
23

fetch-gifs

Fetch GIFS for your nodeJS app in just few steps
JavaScript
7
star
24

30-days-of-code

Daily log of the things I read and learn during week days, and maybe weekends
7
star
25

micro-typeof

✍🏿Get the exact type of a value
TypeScript
7
star
26

vortal

Voice Portal System for information management
JavaScript
6
star
27

ReactAndPreact

Repo to Compare React to React with Preact Compat in terms of speed and performance 🔥 🔥
JavaScript
6
star
28

ademola.adegbuyi.me

Ademola's Portfolio
JavaScript
6
star
29

react-hooks-playground

React Hooks Playground! Yay!!!
JavaScript
5
star
30

component-library

A component library for my article on Smashing Magazine.
JavaScript
5
star
31

react-gif-finder

Example Implemention of Fetch Gif With React
JavaScript
4
star
32

portfolio-2018

My Portfolio
JavaScript
4
star
33

web-workers-demo

Examples using web workers
HTML
3
star
34

react-101

Intro to React class
JavaScript
3
star
35

portfolio-2019-cli

A CLI package for my porfolio 😅
JavaScript
3
star
36

react-integrations

A React library to help integrate Vanilla JS libraries to your app
JavaScript
3
star
37

minifycss

Tiny ~200B minimal css minifier.
JavaScript
3
star
38

headerParser

Header Parser Microservice FCC Challenge
JavaScript
3
star
39

todo-mvc

A todomvc.com example built on RelayJS with @RisingStack/graffiti-mongoose Schema
JavaScript
3
star
40

node-mvrd

😅 Motor Vehicle Registration Data???
JavaScript
3
star
41

react-mdl-css

Use a custom style from https://getmdl.io/customize in your react-mdl app 🔥
CSS
2
star
42

fonsole

Format your browser's console - Add some craziness to it 😏
JavaScript
2
star
43

booktrade

Booktrade BackEnd Project
JavaScript
2
star
44

http2-example

Certificate gen and serving files....
JavaScript
2
star
45

vuex-examples-server

The server used for the gallery vuex example
JavaScript
2
star
46

mnml-calc-cli

A simple CLI calculator app with minimist.
JavaScript
2
star
47

simple-calc-cli

A simple CLI calculator app with commander
JavaScript
2
star
48

Timestamp-Microservice

An Api Project For FreeCodeCamp
JavaScript
2
star
49

fcc-roguelike

FreeCodeCamp RougeLike React Challenge
JavaScript
1
star
50

emotion-force-filter-unset

Chrome extension to forcefully remove filters from emotion documentation
JavaScript
1
star
51

Minidium

Medium Home Clone built with Preact and Webpack 3 for my IO extended session
JavaScript
1
star
52

Auth

BoilerPlate Project For Server Side Authentication
JavaScript
1
star
53

votepush

This is a voting app (NodeJs, Angular, Mongodb)
JavaScript
1
star
54

nightLife

A nightLife Coordination app for FreeCodeCamp BaseJumps
CSS
1
star
55

stockstock

A Realtime Stock Market App (MEAN)
JavaScript
1
star
56

Pinterest-Clone

Real time Pinterest Clone - Built with Meteor and ReactJS
JavaScript
1
star