├── client ├── src │ ├── react-app-env.d.ts │ ├── setupTests.ts │ ├── index.css │ ├── reportWebVitals.ts │ ├── index.tsx │ └── App.tsx ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── .prettierrc ├── .gitignore ├── tsconfig.json ├── package.json └── README.md ├── preview.gif ├── server ├── tsconfig.build.json ├── .env ├── .prettierrc ├── nest-cli.json ├── test │ ├── jest-e2e.json │ └── app.e2e-spec.ts ├── src │ ├── main.ts │ ├── auth │ │ ├── dto │ │ │ └── token.ts │ │ ├── jwt.strategy.ts │ │ ├── jwt-refresh.strategy.ts │ │ ├── auth.service.ts │ │ ├── auth.module.ts │ │ └── auth.resolver.ts │ ├── guards │ │ ├── jwt-auth.guard.ts │ │ └── jwt-refresh-auth.guard.ts │ └── app.module.ts ├── schema.gql ├── .gitignore ├── tsconfig.json ├── .eslintrc.js ├── package.json └── README.md └── README.md /client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /preview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hsk-kr/apollo-graphql-refresh-token/HEAD/preview.gif -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hsk-kr/apollo-graphql-refresh-token/HEAD/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hsk-kr/apollo-graphql-refresh-token/HEAD/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hsk-kr/apollo-graphql-refresh-token/HEAD/client/public/logo512.png -------------------------------------------------------------------------------- /client/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "es5", 3 | "tabWidth": 2, 4 | "semi": true, 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /server/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /server/.env: -------------------------------------------------------------------------------- 1 | ACCESS_TOKEN_SECRET=accesstokensecret 2 | ACCESS_TOKEN_EXPIRATION=5s 3 | REFRESH_TOKEN_SECRET=refreshtokensecret 4 | REFRESH_TOKEN_EXPIRATION=1m -------------------------------------------------------------------------------- /server/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "all", 3 | "tabWidth": 2, 4 | "semi": true, 5 | "singleQuote": true, 6 | "endOfLine": "auto" 7 | } 8 | -------------------------------------------------------------------------------- /server/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /server/test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /client/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /server/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | app.enableCors(); 7 | await app.listen(3000); 8 | } 9 | bootstrap(); 10 | -------------------------------------------------------------------------------- /server/src/auth/dto/token.ts: -------------------------------------------------------------------------------- 1 | import { ObjectType, Field } from '@nestjs/graphql'; 2 | 3 | @ObjectType() 4 | export class CreateTokenResponse { 5 | @Field() 6 | accessToken: string; 7 | 8 | @Field() 9 | refreshToken: string; 10 | } 11 | 12 | @ObjectType() 13 | export class RefreshTokenResponse { 14 | @Field() 15 | accessToken: string; 16 | } 17 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /server/src/guards/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { ExecutionContext, Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | import { GqlExecutionContext } from '@nestjs/graphql'; 4 | 5 | @Injectable() 6 | export class JwtAuthGuard extends AuthGuard('jwt') { 7 | getRequest(context: ExecutionContext) { 8 | const ctx = GqlExecutionContext.create(context); 9 | return ctx.getContext().req; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /server/src/guards/jwt-refresh-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { ExecutionContext, Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | import { GqlExecutionContext } from '@nestjs/graphql'; 4 | 5 | @Injectable() 6 | export class JwtRefreshAuthGuard extends AuthGuard('jwtRefresh') { 7 | getRequest(context: ExecutionContext) { 8 | const ctx = GqlExecutionContext.create(context); 9 | return ctx.getContext().req; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /client/src/reportWebVitals.ts: -------------------------------------------------------------------------------- 1 | import { ReportHandler } from 'web-vitals'; 2 | 3 | const reportWebVitals = (onPerfEntry?: ReportHandler) => { 4 | if (onPerfEntry && onPerfEntry instanceof Function) { 5 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 6 | getCLS(onPerfEntry); 7 | getFID(onPerfEntry); 8 | getFCP(onPerfEntry); 9 | getLCP(onPerfEntry); 10 | getTTFB(onPerfEntry); 11 | }); 12 | } 13 | }; 14 | 15 | export default reportWebVitals; 16 | -------------------------------------------------------------------------------- /server/schema.gql: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------ 2 | # THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY) 3 | # ------------------------------------------------------ 4 | 5 | type CreateTokenResponse { 6 | accessToken: String! 7 | refreshToken: String! 8 | } 9 | 10 | type RefreshTokenResponse { 11 | accessToken: String! 12 | } 13 | 14 | type Query { 15 | ping: Boolean! 16 | } 17 | 18 | type Mutation { 19 | createToken: CreateTokenResponse! 20 | refreshToken: RefreshTokenResponse! 21 | } -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /server/src/auth/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { ExtractJwt, Strategy } from 'passport-jwt'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable } from '@nestjs/common'; 4 | 5 | @Injectable() 6 | export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { 7 | constructor() { 8 | super({ 9 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 10 | ignoreExpiration: false, 11 | secretOrKey: process.env.ACCESS_TOKEN_SECRET, 12 | }); 13 | } 14 | 15 | async validate(payload: any) { 16 | return { user: payload.user }; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apollo GraphQL Refresh Token 2 | 3 | This is an example of how to implement the process to refresh a token when the token is invalid in Apollo GraphQL. 4 | 5 | You can reference the detail in my post ["React Apollo: JWT & Refresh Token"](https://dev.to/lico/react-apollo-refresh-tokens-5h0k) on Dev.to. 6 | 7 | There is another implementation for the refreshing token process used `Link`. Check this out in [the `link` branch](https://github.com/hsk-kr/apollo-graphql-refresh-token/tree/link). 8 | 9 | --- 10 | 11 | ![image](https://github.com/hsk-kr/apollo-graphql-refresh-token/blob/main/preview.gif?raw=true) 12 | -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /server/src/auth/jwt-refresh.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Strategy, ExtractJwt } from 'passport-jwt'; 4 | 5 | @Injectable() 6 | export class JwtRefreshStrategy extends PassportStrategy( 7 | Strategy, 8 | 'jwtRefresh', 9 | ) { 10 | constructor() { 11 | super({ 12 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 13 | ignoreExpiration: false, 14 | secretOrKey: process.env.REFRESH_TOKEN_SECRET, 15 | }); 16 | } 17 | 18 | async validate(payload: any) { 19 | return { user: payload.user }; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | const root = ReactDOM.createRoot( 8 | document.getElementById('root') as HTMLElement 9 | ); 10 | root.render( 11 | 12 | 13 | 14 | ); 15 | 16 | // If you want to start measuring performance in your app, pass a function 17 | // to log results (for example: reportWebVitals(console.log)) 18 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 19 | reportWebVitals(); 20 | -------------------------------------------------------------------------------- /server/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /server/test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /server/src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { JwtService } from '@nestjs/jwt'; 3 | 4 | @Injectable() 5 | export class AuthService { 6 | constructor(private jwtService: JwtService) {} 7 | 8 | async createToken() { 9 | const accessToken = await this.jwtService.signAsync({}); 10 | const refreshToken = await this.jwtService.signAsync( 11 | {}, 12 | { 13 | secret: process.env.REFRESH_TOKEN_SECRET, 14 | expiresIn: process.env.REFRESH_TOKEN_EXPIRATION, 15 | }, 16 | ); 17 | 18 | return { accessToken, refreshToken }; 19 | } 20 | 21 | async refreshToken() { 22 | const accessToken = await this.jwtService.signAsync({}); 23 | return { accessToken }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /server/src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { JwtModule } from '@nestjs/jwt'; 3 | import { AuthService } from './auth.service'; 4 | import { AuthResolver } from './auth.resolver'; 5 | import { JwtStrategy } from './jwt.strategy'; 6 | import { JwtRefreshStrategy } from './jwt-refresh.strategy'; 7 | 8 | @Module({ 9 | imports: [ 10 | // For using environment variables throguh @nestjs/config 11 | JwtModule.registerAsync({ 12 | useFactory: async () => ({ 13 | secret: process.env.ACCESS_TOKEN_SECRET, 14 | signOptions: { 15 | expiresIn: process.env.ACCESS_TOKEN_EXPIRATION, 16 | }, 17 | }), 18 | }), 19 | ], 20 | providers: [AuthResolver, AuthService, JwtStrategy, JwtRefreshStrategy], 21 | }) 22 | export class AuthModule {} 23 | -------------------------------------------------------------------------------- /server/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir: __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | 'prettier/prettier': [ 25 | 'error', 26 | { 27 | endOfLine: 'auto', 28 | }, 29 | ], 30 | }, 31 | }; 32 | -------------------------------------------------------------------------------- /server/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; 2 | import { Module } from '@nestjs/common'; 3 | import { GraphQLModule } from '@nestjs/graphql'; 4 | import { AuthModule } from './auth/auth.module'; 5 | import { ConfigModule } from '@nestjs/config'; 6 | import * as Joi from 'joi'; 7 | 8 | @Module({ 9 | imports: [ 10 | ConfigModule.forRoot({ 11 | isGlobal: true, 12 | validationSchema: Joi.object({ 13 | ACCESS_TOKEN_SECRET: Joi.string().required(), 14 | ACCESS_TOKEN_EXPIRATION: Joi.string().required(), 15 | REFRESH_TOKEN_SECRET: Joi.string().required(), 16 | REFRESH_TOKEN_EXPIRATION: Joi.string().required(), 17 | }), 18 | }), 19 | GraphQLModule.forRoot({ 20 | driver: ApolloDriver, 21 | autoSchemaFile: 'schema.gql', 22 | }), 23 | AuthModule, 24 | ], 25 | }) 26 | export class AppModule {} 27 | -------------------------------------------------------------------------------- /server/src/auth/auth.resolver.ts: -------------------------------------------------------------------------------- 1 | import { UseGuards } from '@nestjs/common'; 2 | import { Mutation, Query, Resolver } from '@nestjs/graphql'; 3 | import { AuthService } from './auth.service'; 4 | import { CreateTokenResponse, RefreshTokenResponse } from './dto/token'; 5 | import { JwtAuthGuard } from '../guards/jwt-auth.guard'; 6 | import { JwtRefreshAuthGuard } from '../guards/jwt-refresh-auth.guard'; 7 | 8 | @Resolver() 9 | export class AuthResolver { 10 | constructor(private readonly authService: AuthService) {} 11 | 12 | @Mutation(() => CreateTokenResponse) 13 | async createToken(): Promise { 14 | return this.authService.createToken(); 15 | } 16 | 17 | @UseGuards(JwtAuthGuard) 18 | @Query(() => Boolean) 19 | async ping() { 20 | return true; 21 | } 22 | 23 | @UseGuards(JwtRefreshAuthGuard) 24 | @Mutation(() => RefreshTokenResponse) 25 | async refreshToken(): Promise { 26 | return this.authService.refreshToken(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@apollo/client": "^3.6.4", 7 | "@emotion/react": "^11.9.0", 8 | "@emotion/styled": "^11.8.1", 9 | "@testing-library/jest-dom": "^5.16.4", 10 | "@testing-library/react": "^13.2.0", 11 | "@testing-library/user-event": "^13.5.0", 12 | "@types/jest": "^27.5.1", 13 | "@types/node": "^16.11.35", 14 | "@types/react": "^18.0.9", 15 | "@types/react-dom": "^18.0.4", 16 | "graphql": "^16.5.0", 17 | "react": "^18.1.0", 18 | "react-dom": "^18.1.0", 19 | "react-scripts": "5.0.1", 20 | "typescript": "^4.6.4", 21 | "web-vitals": "^2.1.4" 22 | }, 23 | "scripts": { 24 | "start": "react-scripts start", 25 | "build": "react-scripts build", 26 | "test": "react-scripts test", 27 | "eject": "react-scripts eject" 28 | }, 29 | "eslintConfig": { 30 | "extends": [ 31 | "react-app", 32 | "react-app/jest" 33 | ] 34 | }, 35 | "browserslist": { 36 | "production": [ 37 | ">0.2%", 38 | "not dead", 39 | "not op_mini all" 40 | ], 41 | "development": [ 42 | "last 1 chrome version", 43 | "last 1 firefox version", 44 | "last 1 safari version" 45 | ] 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "server", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json" 22 | }, 23 | "dependencies": { 24 | "@nestjs/apollo": "^10.0.11", 25 | "@nestjs/common": "^8.0.0", 26 | "@nestjs/config": "^2.0.0", 27 | "@nestjs/core": "^8.0.0", 28 | "@nestjs/graphql": "^10.0.11", 29 | "@nestjs/jwt": "^8.0.0", 30 | "@nestjs/passport": "^8.2.1", 31 | "@nestjs/platform-express": "^8.0.0", 32 | "apollo-server-express": "^3.7.0", 33 | "graphql": "^16.5.0", 34 | "joi": "^17.6.0", 35 | "passport": "^0.5.2", 36 | "passport-jwt": "^4.0.0", 37 | "passport-local": "^1.0.0", 38 | "reflect-metadata": "^0.1.13", 39 | "rimraf": "^3.0.2", 40 | "rxjs": "^7.2.0" 41 | }, 42 | "devDependencies": { 43 | "@nestjs/cli": "^8.0.0", 44 | "@nestjs/schematics": "^8.0.0", 45 | "@nestjs/testing": "^8.0.0", 46 | "@types/express": "^4.17.13", 47 | "@types/jest": "27.5.0", 48 | "@types/joi": "^17.2.3", 49 | "@types/node": "^16.0.0", 50 | "@types/passport-jwt": "^3.0.6", 51 | "@types/passport-local": "^1.0.34", 52 | "@types/supertest": "^2.0.11", 53 | "@typescript-eslint/eslint-plugin": "^5.0.0", 54 | "@typescript-eslint/parser": "^5.0.0", 55 | "eslint": "^8.0.1", 56 | "eslint-config-prettier": "^8.3.0", 57 | "eslint-plugin-prettier": "^4.0.0", 58 | "jest": "28.0.3", 59 | "prettier": "^2.3.2", 60 | "source-map-support": "^0.5.20", 61 | "supertest": "^6.1.3", 62 | "ts-jest": "28.0.1", 63 | "ts-loader": "^9.2.3", 64 | "ts-node": "^10.0.0", 65 | "tsconfig-paths": "4.0.0", 66 | "typescript": "^4.3.5" 67 | }, 68 | "jest": { 69 | "moduleFileExtensions": [ 70 | "js", 71 | "json", 72 | "ts" 73 | ], 74 | "rootDir": "src", 75 | "testRegex": ".*\\.spec\\.ts$", 76 | "transform": { 77 | "^.+\\.(t|j)s$": "ts-jest" 78 | }, 79 | "collectCoverageFrom": [ 80 | "**/*.(t|j)s" 81 | ], 82 | "coverageDirectory": "../coverage", 83 | "testEnvironment": "node" 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 6 | [circleci-url]: https://circleci.com/gh/nestjs/nest 7 | 8 |

A progressive Node.js framework for building efficient and scalable server-side applications.

9 |

10 | NPM Version 11 | Package License 12 | NPM Downloads 13 | CircleCI 14 | Coverage 15 | Discord 16 | Backers on Open Collective 17 | Sponsors on Open Collective 18 | 19 | Support us 20 | 21 |

22 | 24 | 25 | ## Description 26 | 27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 28 | 29 | ## Installation 30 | 31 | ```bash 32 | $ npm install 33 | ``` 34 | 35 | ## Running the app 36 | 37 | ```bash 38 | # development 39 | $ npm run start 40 | 41 | # watch mode 42 | $ npm run start:dev 43 | 44 | # production mode 45 | $ npm run start:prod 46 | ``` 47 | 48 | ## Test 49 | 50 | ```bash 51 | # unit tests 52 | $ npm run test 53 | 54 | # e2e tests 55 | $ npm run test:e2e 56 | 57 | # test coverage 58 | $ npm run test:cov 59 | ``` 60 | 61 | ## Support 62 | 63 | Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). 64 | 65 | ## Stay in touch 66 | 67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 68 | - Website - [https://nestjs.com](https://nestjs.com/) 69 | - Twitter - [@nestframework](https://twitter.com/nestframework) 70 | 71 | ## License 72 | 73 | Nest is [MIT licensed](LICENSE). 74 | -------------------------------------------------------------------------------- /client/src/App.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { 3 | ApolloClient, 4 | InMemoryCache, 5 | ApolloProvider, 6 | FetchResult, 7 | ApolloLink, 8 | useLazyQuery, 9 | createHttpLink, 10 | gql, 11 | useMutation, 12 | GraphQLRequest, 13 | } from '@apollo/client'; 14 | import { onError } from '@apollo/client/link/error'; 15 | import { setContext } from '@apollo/client/link/context'; 16 | import { Observable } from '@apollo/client/utilities'; 17 | import styled from '@emotion/styled/macro'; 18 | import { GraphQLError } from 'graphql'; 19 | 20 | /** 21 | * Types 22 | */ 23 | interface Tokens { 24 | accessToken: string; 25 | refreshToken: string; 26 | } 27 | 28 | interface AccessToken { 29 | accessToken: string; 30 | } 31 | 32 | /** 33 | * Queries 34 | */ 35 | const CREATE_TOKEN = gql` 36 | mutation createToken { 37 | createToken { 38 | accessToken 39 | refreshToken 40 | } 41 | } 42 | `; 43 | 44 | const REFRESH_TOKEN = gql` 45 | mutation refreshToken { 46 | refreshToken { 47 | accessToken 48 | } 49 | } 50 | `; 51 | 52 | const PING = gql` 53 | query ping { 54 | ping 55 | } 56 | `; 57 | 58 | /** 59 | * Apollo Setup 60 | */ 61 | 62 | function isRefreshRequest(operation: GraphQLRequest) { 63 | return operation.operationName === 'refreshToken'; 64 | } 65 | 66 | // Returns accesstoken if opoeration is not a refresh token request 67 | function returnTokenDependingOnOperation(operation: GraphQLRequest) { 68 | if (isRefreshRequest(operation)) 69 | return localStorage.getItem('refreshToken') || ''; 70 | else return localStorage.getItem('accessToken') || ''; 71 | } 72 | 73 | const httpLink = createHttpLink({ 74 | uri: 'http://localhost:3000/graphql', 75 | }); 76 | 77 | const authLink = setContext((operation, { headers }) => { 78 | let token = returnTokenDependingOnOperation(operation); 79 | 80 | return { 81 | headers: { 82 | ...headers, 83 | authorization: token ? `Bearer ${token}` : '', 84 | }, 85 | }; 86 | }); 87 | 88 | const errorLink = onError( 89 | ({ graphQLErrors, networkError, operation, forward }) => { 90 | if (graphQLErrors) { 91 | for (let err of graphQLErrors) { 92 | switch (err.extensions.code) { 93 | case 'UNAUTHENTICATED': 94 | // ignore 401 error for a refresh request 95 | if (operation.operationName === 'refreshToken') return; 96 | 97 | const observable = new Observable>>( 98 | (observer) => { 99 | // used an annonymous function for using an async function 100 | (async () => { 101 | try { 102 | const accessToken = await refreshToken(); 103 | 104 | if (!accessToken) { 105 | throw new GraphQLError('Empty AccessToken'); 106 | } 107 | 108 | // Retry the failed request 109 | const subscriber = { 110 | next: observer.next.bind(observer), 111 | error: observer.error.bind(observer), 112 | complete: observer.complete.bind(observer), 113 | }; 114 | 115 | forward(operation).subscribe(subscriber); 116 | } catch (err) { 117 | observer.error(err); 118 | } 119 | })(); 120 | } 121 | ); 122 | 123 | return observable; 124 | } 125 | } 126 | } 127 | 128 | if (networkError) console.log(`[Network error]: ${networkError}`); 129 | } 130 | ); 131 | 132 | const client = new ApolloClient({ 133 | link: ApolloLink.from([errorLink, authLink, httpLink]), 134 | cache: new InMemoryCache(), 135 | }); 136 | 137 | // Request a refresh token to then stores and returns the accessToken. 138 | const refreshToken = async () => { 139 | try { 140 | const refreshResolverResponse = await client.mutate<{ 141 | refreshToken: AccessToken; 142 | }>({ 143 | mutation: REFRESH_TOKEN, 144 | }); 145 | 146 | const accessToken = refreshResolverResponse.data?.refreshToken.accessToken; 147 | localStorage.setItem('accessToken', accessToken || ''); 148 | return accessToken; 149 | } catch (err) { 150 | localStorage.clear(); 151 | throw err; 152 | } 153 | }; 154 | 155 | /** 156 | * React Components 157 | */ 158 | 159 | function App() { 160 | const [createToken, { data: createTokenData }] = useMutation<{ 161 | createToken: Tokens; 162 | }>(CREATE_TOKEN); 163 | const [ping] = useLazyQuery(PING, { 164 | fetchPolicy: 'network-only', 165 | }); 166 | 167 | const requestToken = () => { 168 | createToken(); 169 | }; 170 | 171 | const sendPing = () => { 172 | ping(); 173 | }; 174 | 175 | useEffect(() => { 176 | if (!createTokenData) return; 177 | 178 | const { accessToken, refreshToken } = createTokenData.createToken; 179 | 180 | // Save tokens in localStorage 181 | localStorage.setItem('accessToken', accessToken); 182 | localStorage.setItem('refreshToken', refreshToken); 183 | }, [createTokenData]); 184 | 185 | return ( 186 | 187 | 190 | 193 | 194 | ); 195 | } 196 | 197 | function ApolloWrapper() { 198 | return ( 199 | 200 | 201 | 202 | ); 203 | } 204 | 205 | /** 206 | * Styles 207 | */ 208 | 209 | const Container = styled.div` 210 | display: flex; 211 | flex-direction: column; 212 | row-gap: 12px; 213 | padding: 24px; 214 | 215 | > button { 216 | width: 200px; 217 | height: 24px; 218 | } 219 | `; 220 | 221 | export default ApolloWrapper; 222 | --------------------------------------------------------------------------------