16 | );
17 | }
18 |
19 | }
20 |
21 | export default Loading;
--------------------------------------------------------------------------------
/src/config/reducers.ts:
--------------------------------------------------------------------------------
1 | import { combineReducers } from 'redux';
2 |
3 | interface DefaultState {}
4 | // tslint:disable-next-line:no-any
5 | function defaultReducer(state: DefaultState = {}, action: any): DefaultState {
6 | return {...state};
7 | }
8 |
9 | // TODO: add reducers here
10 | const combined = combineReducers({
11 | defaultReducer
12 | });
13 |
14 | export default combined;
--------------------------------------------------------------------------------
/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 | "start_url": "./index.html",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/config/firebase.ts:
--------------------------------------------------------------------------------
1 | import * as firebase from 'firebase';
2 |
3 | const config = {
4 | apiKey: '',
5 | authDomain: '',
6 | databaseURL: '',
8 | storageBucket: '',
9 | messagingSenderId: ''
10 | };
11 | firebase.initializeApp(config);
12 |
13 | export default firebase;
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 80px;
8 | }
9 |
10 | .App-header {
11 | background-color: #222;
12 | height: 150px;
13 | padding: 20px;
14 | color: white;
15 | }
16 |
17 | .App-title {
18 | font-size: 1.5em;
19 | }
20 |
21 | .App-intro {
22 | font-size: large;
23 | }
24 |
25 | @keyframes App-logo-spin {
26 | from { transform: rotate(0deg); }
27 | to { transform: rotate(360deg); }
28 | }
29 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "outDir": "build/dist",
4 | "module": "esnext",
5 | "target": "es5",
6 | "lib": ["es6", "dom"],
7 | "sourceMap": true,
8 | "allowJs": true,
9 | "jsx": "react",
10 | "moduleResolution": "node",
11 | "rootDir": "src",
12 | "forceConsistentCasingInFileNames": true,
13 | "noImplicitReturns": true,
14 | "noImplicitThis": true,
15 | "noImplicitAny": true,
16 | "strictNullChecks": true,
17 | "suppressImplicitAnyIndexErrors": true,
18 | "noUnusedLocals": true
19 | },
20 | "exclude": [
21 | "node_modules",
22 | "build",
23 | "scripts",
24 | "acceptance-tests",
25 | "webpack",
26 | "jest",
27 | "src/setupTests.ts"
28 | ]
29 | }
30 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { Router } from 'react-router';
3 | import createBrowserHistory from 'history/createBrowserHistory';
4 | import RouteIndex from './routes/Index';
5 | import { Provider } from 'react-redux';
6 | import ReduxConfig from './config/redux';
7 |
8 | const history = createBrowserHistory();
9 | const reduxConfig = ReduxConfig();
10 |
11 | export interface Props {
12 | }
13 |
14 | export interface State {
15 | }
16 |
17 | class App extends React.Component {
18 |
19 | render() {
20 | return (
21 |
22 |
23 |
24 |
25 |
26 | );
27 | }
28 | }
29 |
30 | export default App;
31 |
--------------------------------------------------------------------------------
/src/config/redux.ts:
--------------------------------------------------------------------------------
1 | import { createStore, applyMiddleware } from 'redux';
2 | // import { persistStore, persistReducer } from 'redux-persist';
3 | import thunk from 'redux-thunk';
4 | import { createLogger } from 'redux-logger';
5 | // defaults to localStorage for web and AsyncStorage for react-native
6 | // import storage from 'redux-persist/lib/storage';
7 | // import CookieStorage from 'redux-persist-cookie-storage';
8 |
9 | import rootReducer from './reducers';
10 |
11 | const logger = createLogger({
12 | // ...options - https://github.com/evgenyrodionov/redux-logger
13 | level: 'log',
14 | duration: true
15 | });
16 |
17 | // const persistConfig = {
18 | // key: 'root',
19 | // storage, // new CookieStorage(),
20 | // blacklist: ['navigation']
21 | // };
22 |
23 | // // See: https://www.npmjs.com/package/redux-persist
24 | // const persistedReducer = persistReducer(persistConfig, rootReducer);
25 |
26 | export default () => {
27 | let store = createStore(rootReducer, applyMiddleware(
28 | thunk,
29 | logger
30 | ));
31 |
32 | return store;
33 | };
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Emergent Bit
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode/
2 |
3 | # Created by https://www.gitignore.io/api/macos,linux,firebase,visualstudiocode,web
4 |
5 | ### Firebase ###
6 | .idea
7 | **/node_modules/*
8 | **/.firebaserc
9 | ### Linux ###
10 | *~
11 |
12 | # temporary files which can be created if a process still has a handle open of a deleted file
13 | .fuse_hidden*
14 |
15 | # KDE directory preferences
16 | .directory
17 |
18 | # Linux trash folder which might appear on any partition or disk
19 | .Trash-*
20 |
21 | # .nfs files are created when an open file is removed but is still being accessed
22 | .nfs*
23 |
24 | ### macOS ###
25 | *.DS_Store
26 | .AppleDouble
27 | .LSOverride
28 |
29 | # Icon must end with two \r
30 | Icon
31 |
32 | # Thumbnails
33 | ._*
34 |
35 | # Files that might appear in the root of a volume
36 | .DocumentRevisions-V100
37 | .fseventsd
38 | .Spotlight-V100
39 | .TemporaryItems
40 | .Trashes
41 | .VolumeIcon.icns
42 | .com.apple.timemachine.donotpresent
43 |
44 | # Directories potentially created on remote AFP share
45 | .AppleDB
46 | .AppleDesktop
47 | Network Trash Folder
48 | Temporary Items
49 | .apdisk
50 |
51 | ### VisualStudioCode ###
52 | .vscode/*
53 | !.vscode/settings.json
54 | !.vscode/tasks.json
55 | !.vscode/launch.json
56 | !.vscode/extensions.json
57 | .history
58 |
59 | # End of https://www.gitignore.io/api/macos,linux,firebase,visualstudiocode,web
60 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ts-auth-ex",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "babel-core": "^6.0.0",
7 | "babel-runtime": "^6.23.0",
8 | "firebase": "^4.12.1",
9 | "query-string": "^6.0.0",
10 | "react": "^16.3.0",
11 | "react-bootstrap": "^0.32.1",
12 | "react-dom": "^16.3.0",
13 | "react-redux": "^5.0.7",
14 | "react-redux-typescript": "^3.0.0-rc.3",
15 | "react-router": "^4.2.0",
16 | "react-router-dom": "^4.2.2",
17 | "react-scripts-ts": "2.14.0",
18 | "redux": "^3.7.2",
19 | "redux-logger": "^3.0.6",
20 | "redux-thunk": "^2.2.0",
21 | "typesafe-actions": "^1.2.0-rc.2",
22 | "utility-types": "^1.1.0"
23 | },
24 | "scripts": {
25 | "start": "react-scripts-ts start",
26 | "build": "react-scripts-ts build",
27 | "test": "react-scripts-ts test --env=jsdom",
28 | "eject": "react-scripts-ts eject"
29 | },
30 | "devDependencies": {
31 | "@types/jest": "^22.2.2",
32 | "@types/node": "^9.6.1",
33 | "@types/query-string": "^5.1.0",
34 | "@types/react": "^16.1.0",
35 | "@types/react-bootstrap": "^0.32.6",
36 | "@types/react-dom": "^16.0.4",
37 | "@types/react-redux": "^5.0.15",
38 | "@types/react-router": "^4.0.23",
39 | "@types/react-router-dom": "^4.2.6",
40 | "@types/redux-logger": "^3.0.5",
41 | "tslint": "^5.9.1",
42 | "typescript": "^2.8.1"
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
22 | React App
23 |
24 |
25 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/routes/Index.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { Route, withRouter } from 'react-router-dom';
3 | import { connect } from 'react-redux';
4 | import { User } from 'firebase';
5 |
6 | import Home from './Home';
7 | import Loading from './Loading';
8 | import firebase from '../config/firebase';
9 |
10 | export interface Props {
11 | // tslint:disable-next-line:no-any
12 | history: any;
13 | // tslint:disable-next-line:no-any
14 | location: any;
15 | }
16 |
17 | export interface State {
18 | signedInUser: User | null;
19 | }
20 |
21 | const REFFERER = 'REFFERER_KEY';
22 |
23 | class Index extends React.Component {
24 |
25 | constructor(props: Props) {
26 | super(props);
27 |
28 | this.state = {
29 | signedInUser: null
30 | };
31 |
32 | this.userStateChange = this.userStateChange.bind(this);
33 |
34 | const currentReffererPath = localStorage.getItem(REFFERER);
35 | if (!currentReffererPath) {
36 | localStorage.setItem(REFFERER, this.props.location.pathname);
37 | } else {
38 | // tslint:disable-next-line:no-console
39 | console.log(currentReffererPath);
40 | }
41 |
42 | firebase.auth().onAuthStateChanged(this.userStateChange);
43 | }
44 |
45 | async componentWillMount() {
46 | firebase.auth().getRedirectResult()
47 | // tslint:disable-next-line:no-any
48 | .then((result: any) => {
49 | // DO NOTHING! Result will be detected by onAuthStateChanged listener
50 | })
51 | .catch(error => {
52 | // tslint:disable-next-line:no-console
53 | console.error(error);
54 | return null;
55 | });
56 | }
57 |
58 | userStateChange(user: User) {
59 | // tslint:disable-next-line:no-console
60 | console.log(user);
61 | if (user) {
62 | // action write user details to redux
63 | this.setState({signedInUser: user});
64 | const redirectToPath = localStorage.getItem(REFFERER);
65 | localStorage.removeItem(REFFERER);
66 | // tslint:disable-next-line:no-console
67 | console.log(redirectToPath);
68 | this.props.history.replace({ pathname: `${redirectToPath}` });
69 | } else {
70 | // action remove user details from redux
71 | const provider = new firebase.auth.GoogleAuthProvider();
72 | // provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
73 | firebase.auth().signInWithRedirect(provider);
74 | }
75 | }
76 |
77 | render() {
78 | if (this.state.signedInUser) {
79 | return (
80 | <>
81 |
82 | {/* Add more routes here */}
83 | >
84 | );
85 | } else {
86 | return ();
87 | }
88 | }
89 | }
90 |
91 | // tslint:disable-next-line:no-any
92 | export function mapStateToProps(state: any, ownProps: any) {
93 | return {
94 | ...ownProps,
95 | };
96 | }
97 |
98 | export default withRouter(connect(mapStateToProps)(Index));
99 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": ["tslint-react"],
3 | "rules": {
4 | "align": [
5 | true,
6 | "parameters",
7 | "arguments",
8 | "statements"
9 | ],
10 | "ban": false,
11 | "class-name": true,
12 | "comment-format": [
13 | true,
14 | "check-space"
15 | ],
16 | "curly": true,
17 | "eofline": false,
18 | "forin": true,
19 | "indent": [ true, "spaces" ],
20 | "interface-name": [true, "never-prefix"],
21 | "jsdoc-format": true,
22 | "jsx-no-lambda": false,
23 | "jsx-no-multiline-js": false,
24 | "label-position": true,
25 | "max-line-length": [ true, 120 ],
26 | "member-ordering": [
27 | true,
28 | "public-before-private",
29 | "static-before-instance",
30 | "variables-before-functions"
31 | ],
32 | "no-any": true,
33 | "no-arg": true,
34 | "no-bitwise": true,
35 | "no-console": [
36 | true,
37 | "log",
38 | "error",
39 | "debug",
40 | "info",
41 | "time",
42 | "timeEnd",
43 | "trace"
44 | ],
45 | "no-consecutive-blank-lines": true,
46 | "no-construct": true,
47 | "no-debugger": true,
48 | "no-duplicate-variable": true,
49 | "no-empty": true,
50 | "no-eval": true,
51 | "no-shadowed-variable": true,
52 | "no-string-literal": true,
53 | "no-switch-case-fall-through": true,
54 | "no-trailing-whitespace": false,
55 | "no-unused-expression": true,
56 | "no-use-before-declare": true,
57 | "one-line": [
58 | true,
59 | "check-catch",
60 | "check-else",
61 | "check-open-brace",
62 | "check-whitespace"
63 | ],
64 | "quotemark": [true, "single", "jsx-double"],
65 | "radix": true,
66 | "semicolon": [true, "always"],
67 | "switch-default": true,
68 |
69 | "trailing-comma": [false],
70 |
71 | "triple-equals": [ true, "allow-null-check" ],
72 | "typedef": [
73 | true,
74 | "parameter",
75 | "property-declaration"
76 | ],
77 | "typedef-whitespace": [
78 | true,
79 | {
80 | "call-signature": "nospace",
81 | "index-signature": "nospace",
82 | "parameter": "nospace",
83 | "property-declaration": "nospace",
84 | "variable-declaration": "nospace"
85 | }
86 | ],
87 | "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore", "allow-pascal-case"],
88 | "whitespace": [
89 | true,
90 | "check-branch",
91 | "check-decl",
92 | "check-module",
93 | "check-operator",
94 | "check-separator",
95 | "check-type",
96 | "check-typecast"
97 | ]
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/src/registerServiceWorker.ts:
--------------------------------------------------------------------------------
1 | // tslint:disable:no-console
2 | // In production, we register a service worker to serve assets from local cache.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on the 'N+1' visit to a page, since previously
7 | // cached resources are updated in the background.
8 |
9 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
10 | // This link also includes instructions on opting out of this behavior.
11 |
12 | const isLocalhost = Boolean(
13 | window.location.hostname === 'localhost' ||
14 | // [::1] is the IPv6 localhost address.
15 | window.location.hostname === '[::1]' ||
16 | // 127.0.0.1/8 is considered localhost for IPv4.
17 | window.location.hostname.match(
18 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
19 | )
20 | );
21 |
22 | export default function register() {
23 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
24 | // The URL constructor is available in all browsers that support SW.
25 | const publicUrl = new URL(
26 | process.env.PUBLIC_URL!,
27 | window.location.toString()
28 | );
29 | if (publicUrl.origin !== window.location.origin) {
30 | // Our service worker won't work if PUBLIC_URL is on a different origin
31 | // from what our page is served on. This might happen if a CDN is used to
32 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
33 | return;
34 | }
35 |
36 | window.addEventListener('load', () => {
37 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
38 |
39 | if (!isLocalhost) {
40 | // Is not local host. Just register service worker
41 | registerValidSW(swUrl);
42 | } else {
43 | // This is running on localhost. Lets check if a service worker still exists or not.
44 | checkValidServiceWorker(swUrl);
45 | }
46 | });
47 | }
48 | }
49 |
50 | function registerValidSW(swUrl: string) {
51 | navigator.serviceWorker
52 | .register(swUrl)
53 | .then(registration => {
54 | registration.onupdatefound = () => {
55 | const installingWorker = registration.installing;
56 | if (installingWorker) {
57 | installingWorker.onstatechange = () => {
58 | if (installingWorker.state === 'installed') {
59 | if (navigator.serviceWorker.controller) {
60 | // At this point, the old content will have been purged and
61 | // the fresh content will have been added to the cache.
62 | // It's the perfect time to display a 'New content is
63 | // available; please refresh.' message in your web app.
64 | console.log('New content is available; please refresh.');
65 | } else {
66 | // At this point, everything has been precached.
67 | // It's the perfect time to display a
68 | // 'Content is cached for offline use.' message.
69 | console.log('Content is cached for offline use.');
70 | }
71 | }
72 | };
73 | }
74 | };
75 | })
76 | .catch(error => {
77 | console.error('Error during service worker registration:', error);
78 | });
79 | }
80 |
81 | function checkValidServiceWorker(swUrl: string) {
82 | // Check if the service worker can be found. If it can't reload the page.
83 | fetch(swUrl)
84 | .then(response => {
85 | // Ensure service worker exists, and that we really are getting a JS file.
86 | if (
87 | response.status === 404 ||
88 | response.headers.get('content-type')!.indexOf('javascript') === -1
89 | ) {
90 | // No service worker found. Probably a different app. Reload the page.
91 | navigator.serviceWorker.ready.then(registration => {
92 | registration.unregister().then(() => {
93 | window.location.reload();
94 | });
95 | });
96 | } else {
97 | // Service worker found. Proceed as normal.
98 | registerValidSW(swUrl);
99 | }
100 | })
101 | .catch(() => {
102 | console.log(
103 | 'No internet connection found. App is running in offline mode.'
104 | );
105 | });
106 | }
107 |
108 | export function unregister() {
109 | if ('serviceWorker' in navigator) {
110 | navigator.serviceWorker.ready.then(registration => {
111 | registration.unregister();
112 | });
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [LIVE DEMO](https://ts-auth-ex.firebaseapp.com/)
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
4 |
5 | It is a typescript implementation created with:
6 | ```sh
7 | create-react-app ts-auth-ex --scripts-version=react-scripts-ts
8 | ```
9 |
10 | # What is this project?
11 |
12 | I got tired of the broken or convoluted methods I was reading about regarding how to manage Firebase authentication within a react app.
13 |
14 | This is an opinionated implementation of a react app that demands a user be signed in before presenting a UI. It uses the Google OAuth2 provider but with very little effort you should be able to use any of the Firebase supported OAuth2 providers.
15 |
16 | There is no logic in the app other than giving a treatment to the signin gate. This is an attempt to add the least amount of logic/code to support a signin gate.
17 |
18 | ## Flow
19 |
20 | 1. User arrives at the site (maybe even a deep path) - save this path to local storage
21 | 2. The routes/Index tries to resolve the firebase user auth
22 | 3. If no user auth then redirect for signin
23 | 4. On redirect result process and let the onAuthStatusChanged pick up the user
24 | 5. On user resolved redirect to original path based on stored path (then remove path from local storage)
25 |
26 | # React boilerplate README
27 |
28 | Below you will find some information on how to perform common tasks.
29 | 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).
30 |
31 | ## Table of Contents
32 |
33 | - [Updating to New Releases](#updating-to-new-releases)
34 | - [Sending Feedback](#sending-feedback)
35 | - [Folder Structure](#folder-structure)
36 | - [Available Scripts](#available-scripts)
37 | - [npm start](#npm-start)
38 | - [npm test](#npm-test)
39 | - [npm run build](#npm-run-build)
40 | - [npm run eject](#npm-run-eject)
41 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
42 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
43 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
44 | - [Debugging in the Editor](#debugging-in-the-editor)
45 | - [Formatting Code Automatically](#formatting-code-automatically)
46 | - [Changing the Page ``](#changing-the-page-title)
47 | - [Installing a Dependency](#installing-a-dependency)
48 | - [Importing a Component](#importing-a-component)
49 | - [Code Splitting](#code-splitting)
50 | - [Adding a Stylesheet](#adding-a-stylesheet)
51 | - [Post-Processing CSS](#post-processing-css)
52 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
53 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
54 | - [Using the `public` Folder](#using-the-public-folder)
55 | - [Changing the HTML](#changing-the-html)
56 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
57 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
58 | - [Using Global Variables](#using-global-variables)
59 | - [Adding Bootstrap](#adding-bootstrap)
60 | - [Using a Custom Theme](#using-a-custom-theme)
61 | - [Adding Flow](#adding-flow)
62 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
63 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
64 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
65 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
66 | - [Can I Use Decorators?](#can-i-use-decorators)
67 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
68 | - [Node](#node)
69 | - [Ruby on Rails](#ruby-on-rails)
70 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
71 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
72 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
73 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
74 | - [Using HTTPS in Development](#using-https-in-development)
75 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
76 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
77 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
78 | - [Running Tests](#running-tests)
79 | - [Filename Conventions](#filename-conventions)
80 | - [Command Line Interface](#command-line-interface)
81 | - [Version Control Integration](#version-control-integration)
82 | - [Writing Tests](#writing-tests)
83 | - [Testing Components](#testing-components)
84 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
85 | - [Initializing Test Environment](#initializing-test-environment)
86 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
87 | - [Coverage Reporting](#coverage-reporting)
88 | - [Continuous Integration](#continuous-integration)
89 | - [Disabling jsdom](#disabling-jsdom)
90 | - [Snapshot Testing](#snapshot-testing)
91 | - [Editor Integration](#editor-integration)
92 | - [Developing Components in Isolation](#developing-components-in-isolation)
93 | - [Getting Started with Storybook](#getting-started-with-storybook)
94 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
95 | - [Making a Progressive Web App](#making-a-progressive-web-app)
96 | - [Opting Out of Caching](#opting-out-of-caching)
97 | - [Offline-First Considerations](#offline-first-considerations)
98 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
99 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
100 | - [Deployment](#deployment)
101 | - [Static Server](#static-server)
102 | - [Other Solutions](#other-solutions)
103 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
104 | - [Building for Relative Paths](#building-for-relative-paths)
105 | - [Azure](#azure)
106 | - [Firebase](#firebase)
107 | - [GitHub Pages](#github-pages)
108 | - [Heroku](#heroku)
109 | - [Netlify](#netlify)
110 | - [Now](#now)
111 | - [S3 and CloudFront](#s3-and-cloudfront)
112 | - [Surge](#surge)
113 | - [Advanced Configuration](#advanced-configuration)
114 | - [Troubleshooting](#troubleshooting)
115 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
116 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
117 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
118 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
119 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
120 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
121 | - [Something Missing?](#something-missing)
122 |
123 | ## Updating to New Releases
124 |
125 | Create React App is divided into two packages:
126 |
127 | * `create-react-app` is a global command-line utility that you use to create new projects.
128 | * `react-scripts` is a development dependency in the generated projects (including this one).
129 |
130 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
131 |
132 | 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.
133 |
134 | 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.
135 |
136 | 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.
137 |
138 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
139 |
140 | ## Sending Feedback
141 |
142 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
143 |
144 | ## Folder Structure
145 |
146 | After creation, your project should look like this:
147 |
148 | ```
149 | my-app/
150 | README.md
151 | node_modules/
152 | package.json
153 | public/
154 | index.html
155 | favicon.ico
156 | src/
157 | App.css
158 | App.js
159 | App.test.js
160 | index.css
161 | index.js
162 | logo.svg
163 | ```
164 |
165 | For the project to build, **these files must exist with exact filenames**:
166 |
167 | * `public/index.html` is the page template;
168 | * `src/index.js` is the JavaScript entry point.
169 |
170 | You can delete or rename the other files.
171 |
172 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
173 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
174 |
175 | Only files inside `public` can be used from `public/index.html`.
176 | Read instructions below for using assets from JavaScript and HTML.
177 |
178 | You can, however, create more top-level directories.
179 | They will not be included in the production build so you can use them for things like documentation.
180 |
181 | ## Available Scripts
182 |
183 | In the project directory, you can run:
184 |
185 | ### `npm start`
186 |
187 | Runs the app in the development mode.
188 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
189 |
190 | The page will reload if you make edits.
191 | You will also see any lint errors in the console.
192 |
193 | ### `npm test`
194 |
195 | Launches the test runner in the interactive watch mode.
196 | See the section about [running tests](#running-tests) for more information.
197 |
198 | ### `npm run build`
199 |
200 | Builds the app for production to the `build` folder.
201 | It correctly bundles React in production mode and optimizes the build for the best performance.
202 |
203 | The build is minified and the filenames include the hashes.
204 | Your app is ready to be deployed!
205 |
206 | See the section about [deployment](#deployment) for more information.
207 |
208 | ### `npm run eject`
209 |
210 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
211 |
212 | 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.
213 |
214 | 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.
215 |
216 | 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.
217 |
218 | ## Supported Language Features and Polyfills
219 |
220 | This project supports a superset of the latest JavaScript standard.
221 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
222 |
223 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
224 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
225 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
226 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
227 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal).
228 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
229 |
230 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
231 |
232 | 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.
233 |
234 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
235 |
236 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
237 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
238 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
239 |
240 | 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.
241 |
242 | ## Syntax Highlighting in the Editor
243 |
244 | 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.
245 |
246 | ## Displaying Lint Output in the Editor
247 |
248 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
249 | >It also only works with npm 3 or higher.
250 |
251 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
252 |
253 | 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.
254 |
255 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
256 |
257 | ```js
258 | {
259 | "extends": "react-app"
260 | }
261 | ```
262 |
263 | Now your editor should report the linting warnings.
264 |
265 | 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.
266 |
267 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
268 |
269 | ## Debugging in the Editor
270 |
271 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
272 |
273 | 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.
274 |
275 | ### Visual Studio Code
276 |
277 | 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.
278 |
279 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
280 |
281 | ```json
282 | {
283 | "version": "0.2.0",
284 | "configurations": [{
285 | "name": "Chrome",
286 | "type": "chrome",
287 | "request": "launch",
288 | "url": "http://localhost:3000",
289 | "webRoot": "${workspaceRoot}/src",
290 | "userDataDir": "${workspaceRoot}/.vscode/chrome",
291 | "sourceMapPathOverrides": {
292 | "webpack:///src/*": "${webRoot}/*"
293 | }
294 | }]
295 | }
296 | ```
297 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
298 |
299 | 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.
300 |
301 | ### WebStorm
302 |
303 | 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.
304 |
305 | 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.
306 |
307 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
308 |
309 | 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.
310 |
311 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
312 |
313 | ## Formatting Code Automatically
314 |
315 | 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/).
316 |
317 | To format our code whenever we make a commit in git, we need to install the following dependencies:
318 |
319 | ```sh
320 | npm install --save husky lint-staged prettier
321 | ```
322 |
323 | Alternatively you may use `yarn`:
324 |
325 | ```sh
326 | yarn add husky lint-staged prettier
327 | ```
328 |
329 | * `husky` makes it easy to use githooks as if they are npm scripts.
330 | * `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).
331 | * `prettier` is the JavaScript formatter we will run before commits.
332 |
333 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
334 |
335 | Add the following line to `scripts` section:
336 |
337 | ```diff
338 | "scripts": {
339 | + "precommit": "lint-staged",
340 | "start": "react-scripts start",
341 | "build": "react-scripts build",
342 | ```
343 |
344 | Next we add a 'lint-staged' field to the `package.json`, for example:
345 |
346 | ```diff
347 | "dependencies": {
348 | // ...
349 | },
350 | + "lint-staged": {
351 | + "src/**/*.{js,jsx,json,css}": [
352 | + "prettier --single-quote --write",
353 | + "git add"
354 | + ]
355 | + },
356 | "scripts": {
357 | ```
358 |
359 | 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.
360 |
361 | 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.
362 |
363 | ## Changing the Page ``
364 |
365 | 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.
366 |
367 | 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.
368 |
369 | 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.
370 |
371 | 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).
372 |
373 | ## Installing a Dependency
374 |
375 | 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`:
376 |
377 | ```sh
378 | npm install --save react-router
379 | ```
380 |
381 | Alternatively you may use `yarn`:
382 |
383 | ```sh
384 | yarn add react-router
385 | ```
386 |
387 | This works for any library, not just `react-router`.
388 |
389 | ## Importing a Component
390 |
391 | This project setup supports ES6 modules thanks to Babel.
392 | 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.
393 |
394 | For example:
395 |
396 | ### `Button.js`
397 |
398 | ```js
399 | import React, { Component } from 'react';
400 |
401 | class Button extends Component {
402 | render() {
403 | // ...
404 | }
405 | }
406 |
407 | export default Button; // Don’t forget to use export default!
408 | ```
409 |
410 | ### `DangerButton.js`
411 |
412 |
413 | ```js
414 | import React, { Component } from 'react';
415 | import Button from './Button'; // Import a component from another file
416 |
417 | class DangerButton extends Component {
418 | render() {
419 | return ;
420 | }
421 | }
422 |
423 | export default DangerButton;
424 | ```
425 |
426 | 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.
427 |
428 | 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'`.
429 |
430 | 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.
431 |
432 | Learn more about ES6 modules:
433 |
434 | * [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)
435 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
436 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
437 |
438 | ## Code Splitting
439 |
440 | 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.
441 |
442 | 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.
443 |
444 | Here is an example:
445 |
446 | ### `moduleA.js`
447 |
448 | ```js
449 | const moduleA = 'Hello';
450 |
451 | export { moduleA };
452 | ```
453 | ### `App.js`
454 |
455 | ```js
456 | import React, { Component } from 'react';
457 |
458 | class App extends Component {
459 | handleClick = () => {
460 | import('./moduleA')
461 | .then(({ moduleA }) => {
462 | // Use moduleA
463 | })
464 | .catch(err => {
465 | // Handle failure
466 | });
467 | };
468 |
469 | render() {
470 | return (
471 |
472 |
473 |
474 | );
475 | }
476 | }
477 |
478 | export default App;
479 | ```
480 |
481 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
482 |
483 | You can also use it with `async` / `await` syntax if you prefer it.
484 |
485 | ### With React Router
486 |
487 | 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).
488 |
489 | ## Adding a Stylesheet
490 |
491 | 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**:
492 |
493 | ### `Button.css`
494 |
495 | ```css
496 | .Button {
497 | padding: 20px;
498 | }
499 | ```
500 |
501 | ### `Button.js`
502 |
503 | ```js
504 | import React, { Component } from 'react';
505 | import './Button.css'; // Tell Webpack that Button.js uses these styles
506 |
507 | class Button extends Component {
508 | render() {
509 | // You can use them as regular CSS styles
510 | return ;
511 | }
512 | }
513 | ```
514 |
515 | **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.
516 |
517 | 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.
518 |
519 | 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.
520 |
521 | ## Post-Processing CSS
522 |
523 | 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.
524 |
525 | For example, this:
526 |
527 | ```css
528 | .App {
529 | display: flex;
530 | flex-direction: row;
531 | align-items: center;
532 | }
533 | ```
534 |
535 | becomes this:
536 |
537 | ```css
538 | .App {
539 | display: -webkit-box;
540 | display: -ms-flexbox;
541 | display: flex;
542 | -webkit-box-orient: horizontal;
543 | -webkit-box-direction: normal;
544 | -ms-flex-direction: row;
545 | flex-direction: row;
546 | -webkit-box-align: center;
547 | -ms-flex-align: center;
548 | align-items: center;
549 | }
550 | ```
551 |
552 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
553 |
554 | ## Adding a CSS Preprocessor (Sass, Less etc.)
555 |
556 | 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 `