├── .babelrc
├── .editorconfig
├── .eslintrc
├── .gitignore
├── .travis.yml
├── DESC.md
├── Makefile
├── README.md
├── example
├── README.md
├── package.json
├── public
│ ├── index.html
│ └── manifest.json
└── src
│ ├── .tern-port
│ ├── App.js
│ ├── TwitchSings_SongList.json
│ ├── example.js
│ ├── index.css
│ └── index.js
├── globals.md
├── header.md
├── modules
├── _test_.md
└── react_oauth2_hook.md
├── package.json
├── rollup.config.js
├── src
├── .eslintrc
├── doc.tsx
├── index.tsx
├── react-storage-hook.d.ts
├── styles.css
├── test.js
├── test.ts
└── typings.d.ts
├── templates
├── pkgdoc_templ.jq
├── readme.hbs
└── readme.jq
├── tsconfig.json
├── tsconfig.test.json
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["env", {
4 | "modules": false
5 | }],
6 | "stage-0",
7 | "react"
8 | ]
9 | }
10 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "parser": "babel-eslint",
3 | "extends": [
4 | "standard",
5 | "standard-react"
6 | ],
7 | "env": {
8 | "es6": true
9 | },
10 | "plugins": [
11 | "react"
12 | ],
13 | "parserOptions": {
14 | "sourceType": "module"
15 | },
16 | "rules": {
17 | // don't force es6 functions to include space before paren
18 | "space-before-function-paren": 0,
19 |
20 | // allow specifying true explicitly for boolean props
21 | "react/jsx-boolean-value": 0
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # See https://help.github.com/ignore-files/ for more about ignoring files.
3 |
4 | # dependencies
5 | node_modules
6 |
7 | # builds
8 | build
9 | dist
10 | .rpt2_cache
11 |
12 | # misc
13 | .DS_Store
14 | .env
15 | .env.local
16 | .env.development.local
17 | .env.test.local
18 | .env.production.local
19 |
20 | npm-debug.log*
21 | yarn-debug.log*
22 | yarn-error.log*
23 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - 9
4 | - 8
5 |
--------------------------------------------------------------------------------
/DESC.md:
--------------------------------------------------------------------------------
1 | ## Overview
2 | This package provides an entirely client-side flow to get OAuth2 implicit grant tokens.
3 | It's implemented as a react hook, [[useOAuth2Token]], with a fairly simple API
4 | and a react component, [[OAuthCallback]] which should be mounted at the
5 | OAuth callback endpoint.
6 |
7 | Take a look at the [Example](#example) for usage information.
8 |
9 | ## Security Considerations
10 | OAuth 2 is a very sensitive protocol. I've done my best to provide good security
11 | guarantees with this package.
12 |
13 | I assume that your application follows reasonable best practices like using `X-Frame-Options`
14 | to prevent clickjacking based attacks.
15 |
16 | ### State
17 | The State token prevents an attacker from forcing a user to sign in as the attacker's
18 | account using a kind of CSRF. Here, I am cautious against multiple types of attacks.
19 |
20 | My state token is not signed, it's a completely static concatenation of some entropy
21 | generated by webcrypto and a key, composed of `JSON.stringify({ authUrl, clientID, scopes })`.
22 | When the callback is recieved by [[OAuthCallback]], it is compared strictly
23 | to the stored value, and otherwise rejected.
24 |
25 | This prevents both attacks where an attacker would try to submit a token to the user's
26 | browser without their consent, and attacks where a malicious OAuth server would
27 | (re)use the n-once to authenticate a callback from a different server.
28 |
29 | ### Timing attacks
30 |
31 | The state token is *not* compared using a fixed-time string comparison.
32 | Where typically, this would lead to an attacker being able to use a lot of time
33 | and statistics to side-channel out the state token, this
34 | should be irrelevant in this configuration, this should be extremely difficult
35 | to pull off accurately as any timing information would be inaccessible or heavily
36 | diluted.
37 |
38 | ## Refresh tokens
39 | This library in-and-of-itself does not acquire long lived refresh tokens. Though
40 | some OAuth servers allow implicit clients to acquire refresh tokens without an
41 | OAuth secret, this isn't part of the OAuth standard. Instead, consider
42 | simply triggering the authorize flow when the token expires -- if the user
43 | is still authorized, the window should almost immediately close. Otherwise,
44 | you can use any special APIs that would let you do this, or skip this library
45 | entirely and try PKCE.
46 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | npm = node_modules/
2 |
3 | dist: src $(wildcard src/*) tsconfig.json
4 | yarn run rollup -c
5 |
6 | .INTERMEDIATE: docs
7 | docs: src/doc.tsx $(wildcard src/*.ts*) $(npm)/typedoc-plugin-markdown
8 | - rm README.md # for some reason it ignores --entrypoint if there's an existing readme...
9 | yarn run typedoc --entryPoint 'react-oauth2-hook' --theme markdown --out docs/
10 | cp docs/* .
11 | rm -r docs
12 |
13 | README.md: docs
14 | # by default, typedoc makes the header of the module a second-level
15 | # header and puts it in a quote. i have no explanation for why
16 | # but this does fix it.
17 | sed -E -i .backup '1s/^> *#(.*)/\1/' README.md
18 | rm $@.backup
19 |
20 | src/doc.tsx: templates/pkgdoc_templ.jq pkginfo.json
21 | jq -r -f $^ > $@
22 |
23 | .INTERMEDIATE: pkginfo.json
24 | pkginfo.json: example/src/example.js DESC.md
25 | jq '[., \
26 | {documentation: $$docs}, \
27 | {example: $$example, examplefile: $$examplefile}, \
28 | {requirements: [.peerDependencies | keys][0] }, \
29 | {year: $$year} \
30 | ] | add' package.json \
31 | --arg docs "$$(cat DESC.md)" \
32 | --arg example "$$(cat $<)" \
33 | --arg examplefile "$$(basename $<)" \
34 | --arg year "$$(date +%Y)" > $@
35 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | > **[react-oauth2-hook](README.md)**
2 |
3 | [Globals]() / [react-oauth2-hook](README.md) /
4 |
5 | **`requires`** immutable
6 |
7 | **`requires`** prop-types
8 |
9 | **`requires`** react
10 |
11 | **`requires`** react-dom
12 |
13 | **`requires`** react-storage-hook
14 |
15 | **`summary`** Retrieve OAuth2 implicit grant tokens purely on the client without destroying application state.
16 |
17 | **`version`** 1.0.11
18 |
19 | **`author`** zemnmez
20 |
21 | **`copyright`** zemnmez 2019
22 |
23 | **`license`** MIT
24 | ## Installation
25 |
26 | ```bash
27 | yarn add react-oauth2-hook
28 | ```
29 | ## Overview
30 | This package provides an entirely client-side flow to get OAuth2 implicit grant tokens.
31 | It's implemented as a react hook, [useOAuth2Token](README.md#const-useoauth2token), with a fairly simple API
32 | and a react component, [OAuthCallback](README.md#const-oauthcallback) which should be mounted at the
33 | OAuth callback endpoint.
34 |
35 | Take a look at the [Example](#example) for usage information.
36 |
37 | ## Security Considerations
38 | OAuth 2 is a very sensitive protocol. I've done my best to provide good security
39 | guarantees with this package.
40 |
41 | I assume that your application follows reasonable best practices like using `X-Frame-Options`
42 | to prevent clickjacking based attacks.
43 |
44 | ### State
45 | The State token prevents an attacker from forcing a user to sign in as the attacker's
46 | account using a kind of CSRF. Here, I am cautious against multiple types of attacks.
47 |
48 | My state token is not signed, it's a completely static concatenation of some entropy
49 | generated by webcrypto and a key, composed of `JSON.stringify({ authUrl, clientID, scopes })`.
50 | When the callback is recieved by [OAuthCallback](README.md#const-oauthcallback), it is compared strictly
51 | to the stored value, and otherwise rejected.
52 |
53 | This prevents both attacks where an attacker would try to submit a token to the user's
54 | browser without their consent, and attacks where a malicious OAuth server would
55 | (re)use the n-once to authenticate a callback from a different server.
56 |
57 | ### Timing attacks
58 |
59 | The state token is *not* compared using a fixed-time string comparison.
60 | Where typically, this would lead to an attacker being able to use a lot of time
61 | and statistics to side-channel out the state token, this
62 | should be irrelevant in this configuration, this should be extremely difficult
63 | to pull off accurately as any timing information would be inaccessible or heavily
64 | diluted.
65 |
66 | ## Refresh tokens
67 | This library in-and-of-itself does not acquire long lived refresh tokens. Though
68 | some OAuth servers allow implicit clients to acquire refresh tokens without an
69 | OAuth secret, this isn't part of the OAuth standard. Instead, consider
70 | simply triggering the authorize flow when the token expires -- if the user
71 | is still authorized, the window should almost immediately close. Otherwise,
72 | you can use any special APIs that would let you do this, or skip this library
73 | entirely and try PKCE.
74 | ## Example
75 |
76 | **`example`**
77 |
78 | ```javascript
79 | import React from 'react'
80 | import { BrowserRouter as Router, Switch } from 'react-router-dom'
81 | import { useOAuth2Token, OAuthCallback } from 'react-oauth2-hook'
82 |
83 | // in this example, we get a Spotify OAuth
84 | // token and use it to show a user's saved
85 | // tracks.
86 |
87 | export default () =>
88 |
89 |
90 |
91 |
92 |
93 |
94 | const SavedTracks = () => {
95 | const [token, getToken] = useOAuth2Token({
96 | authorizeUrl: "https://accounts.spotify.com/authorize",
97 | scope: ["user-library-read"],
98 | clientID: "bd9844d654f242f782509461bdba068c",
99 | redirectUri: document.location.href+"/callback"
100 | })
101 |
102 | const [tracks, setTracks] = React.useState();
103 | const [error, setError] = React.useState();
104 |
105 | // query spotify when we get a token
106 | React.useEffect(() => {
107 | fetch(
108 | 'https://api.spotify.com/v1/me/tracks?limit=50'
109 | ).then(response => response.json()).then(
110 | data => setTracks(data)
111 | ).catch(error => setError(error))
112 | }, [token])
113 |
114 | return
124 | }
125 | ```
126 |
127 | ### Index
128 |
129 | #### Type aliases
130 |
131 | * [OAuthToken](README.md#oauthtoken)
132 | * [getToken](README.md#gettoken)
133 | * [setToken](README.md#settoken)
134 |
135 | #### Variables
136 |
137 | * [ErrIncorrectStateToken](README.md#const-errincorrectstatetoken)
138 | * [ErrNoAccessToken](README.md#const-errnoaccesstoken)
139 |
140 | #### Functions
141 |
142 | * [OAuthCallback](README.md#const-oauthcallback)
143 | * [useOAuth2Token](README.md#const-useoauth2token)
144 |
145 | ## Type aliases
146 |
147 | ### OAuthToken
148 |
149 | Ƭ **OAuthToken**: *string*
150 |
151 | *Defined in [index.tsx:157](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L157)*
152 |
153 | OAuthToken represents an OAuth2 implicit grant token.
154 |
155 | ___
156 |
157 | ### getToken
158 |
159 | Ƭ **getToken**: *function*
160 |
161 | *Defined in [index.tsx:163](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L163)*
162 |
163 | getToken is returned by [useOAuth2Token](README.md#const-useoauth2token).
164 | When called, it prompts the user to authorize.
165 |
166 | #### Type declaration:
167 |
168 | ▸ (): *void*
169 |
170 | ___
171 |
172 | ### setToken
173 |
174 | Ƭ **setToken**: *function*
175 |
176 | *Defined in [index.tsx:171](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L171)*
177 |
178 | setToken is returned by [useOAuth2Token](README.md#const-useoauth2token).
179 | When called, it overwrites any stored OAuth token.
180 | `setToken(undefined)` can be used to synchronously
181 | invalidate all instances of this OAuth token.
182 |
183 | #### Type declaration:
184 |
185 | ▸ (`newValue`: *[OAuthToken](README.md#oauthtoken) | undefined*): *void*
186 |
187 | **Parameters:**
188 |
189 | Name | Type |
190 | ------ | ------ |
191 | `newValue` | [OAuthToken](README.md#oauthtoken) \| undefined |
192 |
193 | ## Variables
194 |
195 | ### `Const` ErrIncorrectStateToken
196 |
197 | • **ErrIncorrectStateToken**: *`Error`* = new Error('incorrect state token')
198 |
199 | *Defined in [index.tsx:210](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L210)*
200 |
201 | This error is thrown by the [OAuthCallback](README.md#const-oauthcallback)
202 | when the state token recieved is incorrect or does not exist.
203 |
204 | ___
205 |
206 | ### `Const` ErrNoAccessToken
207 |
208 | • **ErrNoAccessToken**: *`Error`* = new Error('no access_token')
209 |
210 | *Defined in [index.tsx:216](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L216)*
211 |
212 | This error is thrown by the [OAuthCallback](README.md#const-oauthcallback)
213 | if no access_token is recieved.
214 |
215 | ## Functions
216 |
217 | ### `Const` OAuthCallback
218 |
219 | ▸ **OAuthCallback**(`__namedParameters`: *object*): *`Element`*
220 |
221 | *Defined in [index.tsx:274](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L274)*
222 |
223 | OAuthCallback is a React component that handles the callback
224 | step of the OAuth2 protocol.
225 |
226 | OAuth2Callback is expected to be rendered on the url corresponding
227 | to your redirect_uri.
228 |
229 | By default, this component will deal with errors by closing the window,
230 | via its own React error boundary. Pass `{ errorBoundary: false }`
231 | to handle this functionality yourself.
232 |
233 | **Parameters:**
234 |
235 | ▪ **__namedParameters**: *object*
236 |
237 | Name | Type | Default | Description |
238 | ------ | ------ | ------ | ------ |
239 | `errorBoundary` | boolean | true | When set to true, errors are thrown instead of just closing the window. |
240 |
241 | **Returns:** *`Element`*
242 |
243 | ___
244 |
245 | ### `Const` useOAuth2Token
246 |
247 | ▸ **useOAuth2Token**(`__namedParameters`: *object*): *[[OAuthToken](README.md#oauthtoken) | undefined, [getToken](README.md#gettoken), [setToken](README.md#settoken)]*
248 |
249 | *Defined in [index.tsx:95](https://github.com/Zemnmez/react-oauth2-hook/blob/e142d9b/src/index.tsx#L95)*
250 |
251 | useOAuth2Token is a React hook providing an OAuth2 implicit grant token.
252 |
253 | When useToken is called, it will attempt to retrieve an existing
254 | token by the criteria of `{ authorizeUrl, scopes, clientID }`.
255 | If a token by these specifications does not exist, the first
256 | item in the returned array will be `undefined`.
257 |
258 | If the user wishes to retrieve a new token, they can call `getToken()`,
259 | a function returned by the second parameter. When called, the function
260 | will open a window for the user to confirm the OAuth grant, and
261 | pass it back as expected via the hook.
262 |
263 | The OAuth token must be passed to a static endpoint. As
264 | such, the `callbackUrl` must be passed with this endpoint.
265 | The `callbackUrl` should render the [OAuthCallback](README.md#const-oauthcallback) component,
266 | which will securely verify the token and pass it back,
267 | before closing the window.
268 |
269 | All instances of this hook requesting the same token and scopes
270 | from the same place are synchronised. In concrete terms,
271 | if you have many components waiting for a Facebook OAuth token
272 | to make a call, they will all immediately update when any component
273 | gets a token.
274 |
275 | Finally, in advanced cases the user can manually overwrite any
276 | stored token by capturing and calling the third item in
277 | the reponse array with the new value.
278 |
279 | **Parameters:**
280 |
281 | ▪ **__namedParameters**: *object*
282 |
283 | Name | Type | Default | Description |
284 | ------ | ------ | ------ | ------ |
285 | `authorizeUrl` | string | - | The OAuth authorize URL to retrieve the token from. |
286 | `clientID` | string | - | The OAuth `client_id` corresponding to the requesting client. |
287 | `redirectUri` | string | - | The OAuth `redirect_uri` callback. |
288 | `scope` | string[] | [] | The OAuth scopes to request. |
289 |
290 | **Returns:** *[[OAuthToken](README.md#oauthtoken) | undefined, [getToken](README.md#gettoken), [setToken](README.md#settoken)]*
291 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Updating to New Releases](#updating-to-new-releases)
9 | - [Sending Feedback](#sending-feedback)
10 | - [Folder Structure](#folder-structure)
11 | - [Available Scripts](#available-scripts)
12 | - [npm start](#npm-start)
13 | - [npm test](#npm-test)
14 | - [npm run build](#npm-run-build)
15 | - [npm run eject](#npm-run-eject)
16 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
19 | - [Debugging in the Editor](#debugging-in-the-editor)
20 | - [Formatting Code Automatically](#formatting-code-automatically)
21 | - [Changing the Page ``](#changing-the-page-title)
22 | - [Installing a Dependency](#installing-a-dependency)
23 | - [Importing a Component](#importing-a-component)
24 | - [Code Splitting](#code-splitting)
25 | - [Adding a Stylesheet](#adding-a-stylesheet)
26 | - [Post-Processing CSS](#post-processing-css)
27 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
28 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
29 | - [Using the `public` Folder](#using-the-public-folder)
30 | - [Changing the HTML](#changing-the-html)
31 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
32 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
33 | - [Using Global Variables](#using-global-variables)
34 | - [Adding Bootstrap](#adding-bootstrap)
35 | - [Using a Custom Theme](#using-a-custom-theme)
36 | - [Adding Flow](#adding-flow)
37 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
38 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
39 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
40 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
41 | - [Can I Use Decorators?](#can-i-use-decorators)
42 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
43 | - [Node](#node)
44 | - [Ruby on Rails](#ruby-on-rails)
45 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
46 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
47 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
48 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
49 | - [Using HTTPS in Development](#using-https-in-development)
50 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
51 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
52 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
53 | - [Running Tests](#running-tests)
54 | - [Filename Conventions](#filename-conventions)
55 | - [Command Line Interface](#command-line-interface)
56 | - [Version Control Integration](#version-control-integration)
57 | - [Writing Tests](#writing-tests)
58 | - [Testing Components](#testing-components)
59 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
60 | - [Initializing Test Environment](#initializing-test-environment)
61 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
62 | - [Coverage Reporting](#coverage-reporting)
63 | - [Continuous Integration](#continuous-integration)
64 | - [Disabling jsdom](#disabling-jsdom)
65 | - [Snapshot Testing](#snapshot-testing)
66 | - [Editor Integration](#editor-integration)
67 | - [Developing Components in Isolation](#developing-components-in-isolation)
68 | - [Getting Started with Storybook](#getting-started-with-storybook)
69 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
70 | - [Making a Progressive Web App](#making-a-progressive-web-app)
71 | - [Opting Out of Caching](#opting-out-of-caching)
72 | - [Offline-First Considerations](#offline-first-considerations)
73 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
74 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
75 | - [Deployment](#deployment)
76 | - [Static Server](#static-server)
77 | - [Other Solutions](#other-solutions)
78 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
79 | - [Building for Relative Paths](#building-for-relative-paths)
80 | - [Azure](#azure)
81 | - [Firebase](#firebase)
82 | - [GitHub Pages](#github-pages)
83 | - [Heroku](#heroku)
84 | - [Netlify](#netlify)
85 | - [Now](#now)
86 | - [S3 and CloudFront](#s3-and-cloudfront)
87 | - [Surge](#surge)
88 | - [Advanced Configuration](#advanced-configuration)
89 | - [Troubleshooting](#troubleshooting)
90 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
91 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
92 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
93 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
94 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
95 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
96 | - [Something Missing?](#something-missing)
97 |
98 | ## Updating to New Releases
99 |
100 | Create React App is divided into two packages:
101 |
102 | * `create-react-app` is a global command-line utility that you use to create new projects.
103 | * `react-scripts` is a development dependency in the generated projects (including this one).
104 |
105 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
106 |
107 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
108 |
109 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
110 |
111 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
112 |
113 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
114 |
115 | ## Sending Feedback
116 |
117 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
118 |
119 | ## Folder Structure
120 |
121 | After creation, your project should look like this:
122 |
123 | ```
124 | my-app/
125 | README.md
126 | node_modules/
127 | package.json
128 | public/
129 | index.html
130 | favicon.ico
131 | src/
132 | App.css
133 | App.js
134 | App.test.js
135 | index.css
136 | index.js
137 | logo.svg
138 | ```
139 |
140 | For the project to build, **these files must exist with exact filenames**:
141 |
142 | * `public/index.html` is the page template;
143 | * `src/index.js` is the JavaScript entry point.
144 |
145 | You can delete or rename the other files.
146 |
147 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
148 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
149 |
150 | Only files inside `public` can be used from `public/index.html`.
151 | Read instructions below for using assets from JavaScript and HTML.
152 |
153 | You can, however, create more top-level directories.
154 | They will not be included in the production build so you can use them for things like documentation.
155 |
156 | ## Available Scripts
157 |
158 | In the project directory, you can run:
159 |
160 | ### `npm start`
161 |
162 | Runs the app in the development mode.
163 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
164 |
165 | The page will reload if you make edits.
166 | You will also see any lint errors in the console.
167 |
168 | ### `npm test`
169 |
170 | Launches the test runner in the interactive watch mode.
171 | See the section about [running tests](#running-tests) for more information.
172 |
173 | ### `npm run build`
174 |
175 | Builds the app for production to the `build` folder.
176 | It correctly bundles React in production mode and optimizes the build for the best performance.
177 |
178 | The build is minified and the filenames include the hashes.
179 | Your app is ready to be deployed!
180 |
181 | See the section about [deployment](#deployment) for more information.
182 |
183 | ### `npm run eject`
184 |
185 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
186 |
187 | 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.
188 |
189 | 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.
190 |
191 | 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.
192 |
193 | ## Supported Language Features and Polyfills
194 |
195 | This project supports a superset of the latest JavaScript standard.
196 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
197 |
198 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
199 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
200 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
201 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
202 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal).
203 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
204 |
205 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
206 |
207 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
208 |
209 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
210 |
211 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
212 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
213 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
214 |
215 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
216 |
217 | ## Syntax Highlighting in the Editor
218 |
219 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
220 |
221 | ## Displaying Lint Output in the Editor
222 |
223 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
224 | >It also only works with npm 3 or higher.
225 |
226 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
227 |
228 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
229 |
230 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
231 |
232 | ```js
233 | {
234 | "extends": "react-app"
235 | }
236 | ```
237 |
238 | Now your editor should report the linting warnings.
239 |
240 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
241 |
242 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
243 |
244 | ## Debugging in the Editor
245 |
246 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
247 |
248 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
249 |
250 | ### Visual Studio Code
251 |
252 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
253 |
254 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
255 |
256 | ```json
257 | {
258 | "version": "0.2.0",
259 | "configurations": [{
260 | "name": "Chrome",
261 | "type": "chrome",
262 | "request": "launch",
263 | "url": "http://localhost:3000",
264 | "webRoot": "${workspaceRoot}/src",
265 | "userDataDir": "${workspaceRoot}/.vscode/chrome",
266 | "sourceMapPathOverrides": {
267 | "webpack:///src/*": "${webRoot}/*"
268 | }
269 | }]
270 | }
271 | ```
272 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
273 |
274 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
275 |
276 | ### WebStorm
277 |
278 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
279 |
280 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
281 |
282 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
283 |
284 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
285 |
286 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
287 |
288 | ## Formatting Code Automatically
289 |
290 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
291 |
292 | To format our code whenever we make a commit in git, we need to install the following dependencies:
293 |
294 | ```sh
295 | npm install --save husky lint-staged prettier
296 | ```
297 |
298 | Alternatively you may use `yarn`:
299 |
300 | ```sh
301 | yarn add husky lint-staged prettier
302 | ```
303 |
304 | * `husky` makes it easy to use githooks as if they are npm scripts.
305 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
306 | * `prettier` is the JavaScript formatter we will run before commits.
307 |
308 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
309 |
310 | Add the following line to `scripts` section:
311 |
312 | ```diff
313 | "scripts": {
314 | + "precommit": "lint-staged",
315 | "start": "react-scripts start",
316 | "build": "react-scripts build",
317 | ```
318 |
319 | Next we add a 'lint-staged' field to the `package.json`, for example:
320 |
321 | ```diff
322 | "dependencies": {
323 | // ...
324 | },
325 | + "lint-staged": {
326 | + "src/**/*.{js,jsx,json,css}": [
327 | + "prettier --single-quote --write",
328 | + "git add"
329 | + ]
330 | + },
331 | "scripts": {
332 | ```
333 |
334 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time.
335 |
336 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page.
337 |
338 | ## Changing the Page ``
339 |
340 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
341 |
342 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
343 |
344 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
345 |
346 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
347 |
348 | ## Installing a Dependency
349 |
350 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
351 |
352 | ```sh
353 | npm install --save react-router
354 | ```
355 |
356 | Alternatively you may use `yarn`:
357 |
358 | ```sh
359 | yarn add react-router
360 | ```
361 |
362 | This works for any library, not just `react-router`.
363 |
364 | ## Importing a Component
365 |
366 | This project setup supports ES6 modules thanks to Babel.
367 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
368 |
369 | For example:
370 |
371 | ### `Button.js`
372 |
373 | ```js
374 | import React, { Component } from 'react';
375 |
376 | class Button extends Component {
377 | render() {
378 | // ...
379 | }
380 | }
381 |
382 | export default Button; // Don’t forget to use export default!
383 | ```
384 |
385 | ### `DangerButton.js`
386 |
387 |
388 | ```js
389 | import React, { Component } from 'react';
390 | import Button from './Button'; // Import a component from another file
391 |
392 | class DangerButton extends Component {
393 | render() {
394 | return ;
395 | }
396 | }
397 |
398 | export default DangerButton;
399 | ```
400 |
401 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
402 |
403 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
404 |
405 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
406 |
407 | Learn more about ES6 modules:
408 |
409 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
410 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
411 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
412 |
413 | ## Code Splitting
414 |
415 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
416 |
417 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
418 |
419 | Here is an example:
420 |
421 | ### `moduleA.js`
422 |
423 | ```js
424 | const moduleA = 'Hello';
425 |
426 | export { moduleA };
427 | ```
428 | ### `App.js`
429 |
430 | ```js
431 | import React, { Component } from 'react';
432 |
433 | class App extends Component {
434 | handleClick = () => {
435 | import('./moduleA')
436 | .then(({ moduleA }) => {
437 | // Use moduleA
438 | })
439 | .catch(err => {
440 | // Handle failure
441 | });
442 | };
443 |
444 | render() {
445 | return (
446 |
447 |
448 |
449 | );
450 | }
451 | }
452 |
453 | export default App;
454 | ```
455 |
456 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
457 |
458 | You can also use it with `async` / `await` syntax if you prefer it.
459 |
460 | ### With React Router
461 |
462 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
463 |
464 | ## Adding a Stylesheet
465 |
466 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
467 |
468 | ### `Button.css`
469 |
470 | ```css
471 | .Button {
472 | padding: 20px;
473 | }
474 | ```
475 |
476 | ### `Button.js`
477 |
478 | ```js
479 | import React, { Component } from 'react';
480 | import './Button.css'; // Tell Webpack that Button.js uses these styles
481 |
482 | class Button extends Component {
483 | render() {
484 | // You can use them as regular CSS styles
485 | return ;
486 | }
487 | }
488 | ```
489 |
490 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
491 |
492 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
493 |
494 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
495 |
496 | ## Post-Processing CSS
497 |
498 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
499 |
500 | For example, this:
501 |
502 | ```css
503 | .App {
504 | display: flex;
505 | flex-direction: row;
506 | align-items: center;
507 | }
508 | ```
509 |
510 | becomes this:
511 |
512 | ```css
513 | .App {
514 | display: -webkit-box;
515 | display: -ms-flexbox;
516 | display: flex;
517 | -webkit-box-orient: horizontal;
518 | -webkit-box-direction: normal;
519 | -ms-flex-direction: row;
520 | flex-direction: row;
521 | -webkit-box-align: center;
522 | -ms-flex-align: center;
523 | align-items: center;
524 | }
525 | ```
526 |
527 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
528 |
529 | ## Adding a CSS Preprocessor (Sass, Less etc.)
530 |
531 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `