├── src ├── react-app-env.d.ts ├── setupTests.ts ├── features │ ├── spotifyExample │ │ ├── SpotifyExample.module.css │ │ ├── SpotifyExample.tsx │ │ └── spotifyExampleSlice.ts │ ├── authorization │ │ ├── authorizationSlice.ts │ │ └── Authorization.tsx │ └── counter │ │ ├── Counter.module.css │ │ ├── Counter.tsx │ │ └── counterSlice.ts ├── index.css ├── oauthConfig.ts ├── App.test.tsx ├── utils │ └── hashUtils.ts ├── index.tsx ├── app │ └── store.ts ├── App.css ├── logo.svg ├── App.tsx └── serviceWorker.ts ├── public ├── robots.txt ├── favicon.ico ├── logo192.png ├── logo512.png ├── manifest.json └── index.html ├── .env.local_EXAMPLE ├── .gitignore ├── tsconfig.json ├── package.json └── README.md /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /.env.local_EXAMPLE: -------------------------------------------------------------------------------- 1 | REACT_APP_SPOTIFY_CLIENT_ID='YOUR CLIENT ID' 2 | REACT_APP_REDIRECT_URI=http://localhost:3000 3 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OskarAsplin/react-ts-redux-oauth2-template/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OskarAsplin/react-ts-redux-oauth2-template/HEAD/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OskarAsplin/react-ts-redux-oauth2-template/HEAD/public/logo512.png -------------------------------------------------------------------------------- /src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/features/spotifyExample/SpotifyExample.module.css: -------------------------------------------------------------------------------- 1 | .column { 2 | display: flex; 3 | flex-direction: column; 4 | align-items: center; 5 | justify-content: center; 6 | margin-bottom: 16px; 7 | } 8 | 9 | .row { 10 | display: flex; 11 | align-items: center; 12 | justify-content: center; 13 | margin-top: 16px; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/oauthConfig.ts: -------------------------------------------------------------------------------- 1 | const authEndpoint = 'https://accounts.spotify.com/authorize'; 2 | 3 | const scopes = [ 4 | 'user-read-private', 5 | ]; 6 | 7 | export const getAuthorizeHref = (): string => { 8 | const clientId = process.env.REACT_APP_SPOTIFY_CLIENT_ID; 9 | const redirectUri = process.env.REACT_APP_REDIRECT_URI; 10 | return `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join("%20")}&response_type=token`; 11 | } 12 | -------------------------------------------------------------------------------- /src/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import { Provider } from 'react-redux'; 4 | import { store } from './app/store'; 5 | import App from './App'; 6 | 7 | test('renders learn react link', () => { 8 | const { getByText } = render( 9 | 10 | 11 | 12 | ); 13 | 14 | expect(getByText(/learn/i)).toBeInTheDocument(); 15 | }); 16 | -------------------------------------------------------------------------------- /src/utils/hashUtils.ts: -------------------------------------------------------------------------------- 1 | export const getHashParams = () => { 2 | return window.location.hash 3 | .substring(1) 4 | .split("&") 5 | .reduce(function(initial: { [key: string]: any; }, item) { 6 | if (item) { 7 | var parts = item.split("="); 8 | initial[parts[0]] = decodeURIComponent(parts[1]); 9 | } 10 | return initial; 11 | }, {}); 12 | } 13 | 14 | export const removeHashParamsFromUrl = () => { 15 | window.history.pushState("", document.title, window.location.pathname + window.location.search); 16 | } 17 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": true, 20 | "jsx": "react", 21 | "noFallthroughCasesInSwitch": true 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /src/features/spotifyExample/SpotifyExample.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector } from 'react-redux'; 3 | import { selectDisplayName, selectProduct } from './spotifyExampleSlice'; 4 | import styles from './SpotifyExample.module.css'; 5 | 6 | export function SpotifyExample() { 7 | const displayName = useSelector(selectDisplayName); 8 | const product = useSelector(selectProduct); 9 | 10 | return ( 11 |
12 | {displayName &&
13 | Logged in as: {displayName} 14 |
} 15 | {product &&
16 | Subscription type: {product} 17 |
} 18 |
19 | ); 20 | } 21 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import { store } from './app/store'; 6 | import { Provider } from 'react-redux'; 7 | import * as serviceWorker from './serviceWorker'; 8 | 9 | ReactDOM.render( 10 | 11 | 12 | 13 | 14 | , 15 | document.getElementById('root') 16 | ); 17 | 18 | // If you want your app to work offline and load faster, you can change 19 | // unregister() to register() below. Note this comes with some pitfalls. 20 | // Learn more about service workers: https://bit.ly/CRA-PWA 21 | serviceWorker.unregister(); 22 | -------------------------------------------------------------------------------- /src/app/store.ts: -------------------------------------------------------------------------------- 1 | import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'; 2 | import counterReducer from '../features/counter/counterSlice'; 3 | import authorizationReducer from '../features/authorization/authorizationSlice'; 4 | import spotifyExampleReducer from '../features/spotifyExample/spotifyExampleSlice'; 5 | 6 | export const store = configureStore({ 7 | reducer: { 8 | counter: counterReducer, 9 | authorization: authorizationReducer, 10 | spotifyExample: spotifyExampleReducer, 11 | }, 12 | }); 13 | 14 | export type RootState = ReturnType; 15 | export type AppThunk = ThunkAction< 16 | ReturnType, 17 | RootState, 18 | unknown, 19 | Action 20 | >; 21 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-float infinite 3s ease-in-out; 13 | } 14 | } 15 | 16 | .App-header { 17 | min-height: 100vh; 18 | display: flex; 19 | flex-direction: column; 20 | align-items: center; 21 | justify-content: center; 22 | font-size: calc(10px + 2vmin); 23 | } 24 | 25 | .App-link { 26 | color: rgb(112, 76, 182); 27 | } 28 | 29 | @keyframes App-logo-float { 30 | 0% { 31 | transform: translateY(0); 32 | } 33 | 50% { 34 | transform: translateY(10px) 35 | } 36 | 100% { 37 | transform: translateY(0px) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test3", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@reduxjs/toolkit": "^1.5.0", 7 | "@testing-library/jest-dom": "^4.2.4", 8 | "@testing-library/react": "^9.5.0", 9 | "@testing-library/user-event": "^7.2.1", 10 | "@types/jest": "^24.9.1", 11 | "@types/node": "^12.19.16", 12 | "@types/react": "^16.14.3", 13 | "@types/react-dom": "^16.9.10", 14 | "@types/react-redux": "^7.1.16", 15 | "dotenv": "^8.2.0", 16 | "react": "^16.14.0", 17 | "react-dom": "^16.14.0", 18 | "react-redux": "^7.2.2", 19 | "react-scripts": "^4.0.2", 20 | "typescript": "^3.9.7" 21 | }, 22 | "scripts": { 23 | "start": "react-scripts start", 24 | "build": "react-scripts build", 25 | "test": "react-scripts test", 26 | "eject": "react-scripts eject" 27 | }, 28 | "eslintConfig": { 29 | "extends": "react-app" 30 | }, 31 | "browserslist": { 32 | "production": [ 33 | ">0.2%", 34 | "not dead", 35 | "not op_mini all" 36 | ], 37 | "development": [ 38 | "last 1 chrome version", 39 | "last 1 firefox version", 40 | "last 1 safari version" 41 | ] 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/features/authorization/authorizationSlice.ts: -------------------------------------------------------------------------------- 1 | import { createSlice, PayloadAction } from '@reduxjs/toolkit'; 2 | import { RootState } from '../../app/store'; 3 | 4 | interface AuthorizationState { 5 | loggedIn: boolean; 6 | accessToken: string; 7 | tokenExpiryDate: string; 8 | } 9 | 10 | const initialState: AuthorizationState = { 11 | loggedIn: false, 12 | accessToken: '', 13 | tokenExpiryDate: '', 14 | }; 15 | 16 | export const authorizationSlice = createSlice({ 17 | name: 'authorization', 18 | initialState, 19 | reducers: { 20 | setLoggedIn: (state, action: PayloadAction) => { 21 | state.loggedIn = action.payload; 22 | }, 23 | setAccessToken: (state, action: PayloadAction) => { 24 | state.accessToken = action.payload; 25 | }, 26 | setTokenExpiryDate: (state, action: PayloadAction) => { 27 | const date = new Date() 28 | date.setSeconds(date.getSeconds() + action.payload); 29 | state.tokenExpiryDate = date.toISOString(); 30 | }, 31 | }, 32 | }); 33 | 34 | export const { setLoggedIn, setAccessToken, setTokenExpiryDate } = authorizationSlice.actions; 35 | 36 | export const selectIsLoggedIn = (state: RootState) => state.authorization.loggedIn; 37 | export const selectAccessToken = (state: RootState) => state.authorization.accessToken; 38 | export const selectTokenExpiryDate = (state: RootState) => state.authorization.tokenExpiryDate; 39 | 40 | export default authorizationSlice.reducer; 41 | -------------------------------------------------------------------------------- /src/features/counter/Counter.module.css: -------------------------------------------------------------------------------- 1 | .row { 2 | display: flex; 3 | align-items: center; 4 | justify-content: center; 5 | } 6 | 7 | .row:not(:last-child) { 8 | margin-bottom: 16px; 9 | } 10 | 11 | .value { 12 | font-size: 78px; 13 | padding-left: 16px; 14 | padding-right: 16px; 15 | margin-top: 2px; 16 | font-family: 'Courier New', Courier, monospace; 17 | } 18 | 19 | .button { 20 | appearance: none; 21 | background: none; 22 | font-size: 32px; 23 | padding-left: 12px; 24 | padding-right: 12px; 25 | outline: none; 26 | border: 2px solid transparent; 27 | color: rgb(112, 76, 182); 28 | padding-bottom: 4px; 29 | cursor: pointer; 30 | background-color: rgba(112, 76, 182, 0.1); 31 | border-radius: 2px; 32 | transition: all 0.15s; 33 | } 34 | 35 | .textbox { 36 | font-size: 32px; 37 | padding: 2px; 38 | width: 64px; 39 | text-align: center; 40 | margin-right: 8px; 41 | } 42 | 43 | .button:hover, .button:focus { 44 | border: 2px solid rgba(112, 76, 182, 0.4); 45 | } 46 | 47 | .button:active { 48 | background-color: rgba(112, 76, 182, 0.2); 49 | } 50 | 51 | .asyncButton { 52 | composes: button; 53 | position: relative; 54 | margin-left: 8px; 55 | } 56 | 57 | .asyncButton:after { 58 | content: ""; 59 | background-color: rgba(112, 76, 182, 0.15); 60 | display: block; 61 | position: absolute; 62 | width: 100%; 63 | height: 100%; 64 | left: 0; 65 | top: 0; 66 | opacity: 0; 67 | transition: width 1s linear, opacity 0.5s ease 1s; 68 | } 69 | 70 | .asyncButton:active:after { 71 | width: 0%; 72 | opacity: 1; 73 | transition: 0s 74 | } 75 | -------------------------------------------------------------------------------- /src/features/authorization/Authorization.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { useSelector, useDispatch } from 'react-redux'; 3 | import { 4 | setLoggedIn, 5 | setAccessToken, 6 | setTokenExpiryDate, 7 | selectIsLoggedIn, 8 | selectTokenExpiryDate, 9 | } from './authorizationSlice'; 10 | import { setUserProfileAsync } from '../spotifyExample/spotifyExampleSlice'; 11 | import styles from '../counter/Counter.module.css'; 12 | import { getAuthorizeHref } from '../../oauthConfig'; 13 | import { getHashParams, removeHashParamsFromUrl } from '../../utils/hashUtils'; 14 | 15 | const hashParams = getHashParams(); 16 | const access_token = hashParams.access_token; 17 | const expires_in = hashParams.expires_in; 18 | removeHashParamsFromUrl(); 19 | 20 | export function Authorization() { 21 | const isLoggedIn = useSelector(selectIsLoggedIn); 22 | const tokenExpiryDate = useSelector(selectTokenExpiryDate); 23 | const dispatch = useDispatch(); 24 | 25 | useEffect(() => { 26 | if (access_token) { 27 | dispatch(setLoggedIn(true)); 28 | dispatch(setAccessToken(access_token)); 29 | dispatch(setTokenExpiryDate(Number(expires_in))); 30 | dispatch(setUserProfileAsync(access_token)); 31 | } 32 | // eslint-disable-next-line react-hooks/exhaustive-deps 33 | }, []); 34 | 35 | return ( 36 |
37 |
38 | {!isLoggedIn && 39 | } 46 | {isLoggedIn &&
Token expiry date: {tokenExpiryDate}
} 47 |
48 |
49 | ); 50 | } 51 | -------------------------------------------------------------------------------- /src/features/counter/Counter.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { useSelector, useDispatch } from 'react-redux'; 3 | import { 4 | decrement, 5 | increment, 6 | incrementByAmount, 7 | incrementAsync, 8 | selectCount, 9 | } from './counterSlice'; 10 | import styles from './Counter.module.css'; 11 | 12 | export function Counter() { 13 | const count = useSelector(selectCount); 14 | const dispatch = useDispatch(); 15 | const [incrementAmount, setIncrementAmount] = useState('2'); 16 | 17 | return ( 18 |
19 |
20 | 27 | {count} 28 | 35 |
36 |
37 | setIncrementAmount(e.target.value)} 42 | /> 43 | 51 | 57 |
58 |
59 | ); 60 | } 61 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.svg'; 3 | import { Counter } from './features/counter/Counter'; 4 | import { Authorization } from './features/authorization/Authorization'; 5 | import { SpotifyExample } from './features/spotifyExample/SpotifyExample'; 6 | import './App.css'; 7 | 8 | function App() { 9 | return ( 10 |
11 |
12 | logo 13 | 14 | 15 | 16 |

17 | Edit src/App.tsx and save to reload. 18 |

19 | 20 | Learn 21 | 27 | React 28 | 29 | , 30 | 36 | Redux 37 | 38 | , 39 | 45 | Redux Toolkit 46 | 47 | , and 48 | 54 | React Redux 55 | 56 | 57 |
58 |
59 | ); 60 | } 61 | 62 | export default App; 63 | -------------------------------------------------------------------------------- /src/features/spotifyExample/spotifyExampleSlice.ts: -------------------------------------------------------------------------------- 1 | import { createSlice, PayloadAction } from '@reduxjs/toolkit'; 2 | import { AppThunk, RootState } from '../../app/store'; 3 | import { 4 | setLoggedIn 5 | } from '../../features/authorization/authorizationSlice'; 6 | 7 | interface SpotifyExampleState { 8 | displayName: string, 9 | product: string 10 | } 11 | 12 | const initialState: SpotifyExampleState = { 13 | displayName: '', 14 | product: '', 15 | }; 16 | 17 | export const spotifyexampleSlice = createSlice({ 18 | name: 'spotifyExample', 19 | initialState, 20 | reducers: { 21 | setDisplayName: (state, action: PayloadAction) => { 22 | state.displayName = action.payload; 23 | }, 24 | setProduct: (state, action: PayloadAction) => { 25 | state.product = action.payload; 26 | }, 27 | }, 28 | }); 29 | 30 | export const { setDisplayName, setProduct } = spotifyexampleSlice.actions; 31 | 32 | export const selectDisplayName = (state: RootState) => state.spotifyExample.displayName; 33 | export const selectProduct = (state: RootState) => state.spotifyExample.product; 34 | 35 | export const setUserProfileAsync = (accessToken: string): AppThunk => dispatch => { 36 | const myHeaders = new Headers(); 37 | myHeaders.append('Authorization', 'Bearer ' + accessToken); 38 | 39 | fetch('https://api.spotify.com/v1/me', { 40 | method: 'GET', 41 | headers: myHeaders, 42 | }).then(response => response.json()) 43 | .then((data) => { 44 | console.log(data); 45 | dispatch(setDisplayName(data.display_name ? data.display_name : data.id)); 46 | dispatch(setProduct(data.product)); 47 | }).catch((error) => { 48 | console.log(error); 49 | if (error instanceof XMLHttpRequest) { 50 | if (error.status === 401) { 51 | dispatch(setLoggedIn(false)); 52 | } 53 | } 54 | }); 55 | }; 56 | 57 | export default spotifyexampleSlice.reducer; 58 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React Redux App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/features/counter/counterSlice.ts: -------------------------------------------------------------------------------- 1 | import { createSlice, PayloadAction } from '@reduxjs/toolkit'; 2 | import { AppThunk, RootState } from '../../app/store'; 3 | 4 | interface CounterState { 5 | value: number; 6 | } 7 | 8 | const initialState: CounterState = { 9 | value: 0, 10 | }; 11 | 12 | export const counterSlice = createSlice({ 13 | name: 'counter', 14 | initialState, 15 | reducers: { 16 | increment: state => { 17 | // Redux Toolkit allows us to write "mutating" logic in reducers. It 18 | // doesn't actually mutate the state because it uses the Immer library, 19 | // which detects changes to a "draft state" and produces a brand new 20 | // immutable state based off those changes 21 | state.value += 1; 22 | }, 23 | decrement: state => { 24 | state.value -= 1; 25 | }, 26 | // Use the PayloadAction type to declare the contents of `action.payload` 27 | incrementByAmount: (state, action: PayloadAction) => { 28 | state.value += action.payload; 29 | }, 30 | }, 31 | }); 32 | 33 | export const { increment, decrement, incrementByAmount } = counterSlice.actions; 34 | 35 | // The function below is called a thunk and allows us to perform async logic. It 36 | // can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This 37 | // will call the thunk with the `dispatch` function as the first argument. Async 38 | // code can then be executed and other actions can be dispatched 39 | export const incrementAsync = (amount: number): AppThunk => dispatch => { 40 | setTimeout(() => { 41 | dispatch(incrementByAmount(amount)); 42 | }, 1000); 43 | }; 44 | 45 | // The function below is called a selector and allows us to select a value from 46 | // the state. Selectors can also be defined inline where they're used instead of 47 | // in the slice file. For example: `useSelector((state: RootState) => state.counter.value)` 48 | export const selectCount = (state: RootState) => state.counter.value; 49 | 50 | export default counterSlice.reducer; 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## ⚠️ ARCHIVED - NOT RECOMMENDED 2 | 3 | This repository is archived and I do not recommend using this approach anymore. My recommendation as of 2025 for modern React applications: 4 | 5 | - **For API handling**: Use [TanStack Query](https://tanstack.com/query) 6 | - **For global state management**: Use [Zustand](https://github.com/pmndrs/zustand) 7 | 8 | --- 9 | 10 | A React app template written in Typescript with Redux store and OAuth 2.0. Does not require any server running. The authorization example in the template is for the [Spotify Web API](https://developer.spotify.com/documentation/web-api/) but can be used for any service with the same authorization flow. 11 | 12 | Tutorial on Medium: [medium.com/@oskarasplin/create-a-react-app-with-typescript-redux-and-oauth-2-0-7f62d57890df](https://medium.com/@oskarasplin/create-a-react-app-with-typescript-redux-and-oauth-2-0-7f62d57890df) 13 | 14 | ### Use with Spotify 15 | Register your app [here](https://developer.spotify.com/documentation/web-api) to retrieve a client ID and add http://localhost:3000 to Redirect URIs in the app settings. 16 | 17 | ### Use with other services 18 | Edit the files in src/features/spotifyExample/ to fit your scenario. Or remove the example by removing `` from App.tsx and `spotifyExample: spotifyExampleReducer` from store.ts. 19 | 20 | ## Try it out 21 | 22 | 1. Clone the repository 23 | 2. Navigate to the root directory of the repository 24 | 3. `npm install` 25 | 4. `cp .env.local_EXAMPLE .env.local` and fill `REACT_APP_SPOTIFY_CLIENT_ID` with your client id 26 | 5. `npm start` 27 | 28 | ### Template built with 29 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the official Typescript and Redux template: https://github.com/reduxjs/cra-template-redux-typescript 30 | 31 | # Create React App standard build notes: 32 | 33 | ## Available Scripts 34 | 35 | In the project directory, you can run: 36 | 37 | ### `npm start` 38 | 39 | Runs the app in the development mode.
40 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 41 | 42 | The page will reload if you make edits.
43 | You will also see any lint errors in the console. 44 | 45 | ### `npm test` 46 | 47 | Launches the test runner in the interactive watch mode.
48 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 49 | 50 | ### `npm run build` 51 | 52 | Builds the app for production to the `build` folder.
53 | It correctly bundles React in production mode and optimizes the build for the best performance. 54 | 55 | The build is minified and the filenames include the hashes.
56 | Your app is ready to be deployed! 57 | 58 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 59 | 60 | ### `npm run eject` 61 | 62 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 63 | 64 | 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. 65 | 66 | 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. 67 | 68 | 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. 69 | 70 | ## Learn More 71 | 72 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 73 | 74 | To learn React, check out the [React documentation](https://reactjs.org/). 75 | -------------------------------------------------------------------------------- /src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 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 subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 32 | if (publicUrl.origin !== window.location.origin) { 33 | // Our service worker won't work if PUBLIC_URL is on a different origin 34 | // from what our page is served on. This might happen if a CDN is used to 35 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 36 | return; 37 | } 38 | 39 | window.addEventListener('load', () => { 40 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 41 | 42 | if (isLocalhost) { 43 | // This is running on localhost. Let's check if a service worker still exists or not. 44 | checkValidServiceWorker(swUrl, config); 45 | 46 | // Add some additional logging to localhost, pointing developers to the 47 | // service worker/PWA documentation. 48 | navigator.serviceWorker.ready.then(() => { 49 | console.log( 50 | 'This web app is being served cache-first by a service ' + 51 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 52 | ); 53 | }); 54 | } else { 55 | // Is not localhost. Just register service worker 56 | registerValidSW(swUrl, config); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | function registerValidSW(swUrl: string, config?: Config) { 63 | navigator.serviceWorker 64 | .register(swUrl) 65 | .then(registration => { 66 | registration.onupdatefound = () => { 67 | const installingWorker = registration.installing; 68 | if (installingWorker == null) { 69 | return; 70 | } 71 | installingWorker.onstatechange = () => { 72 | if (installingWorker.state === 'installed') { 73 | if (navigator.serviceWorker.controller) { 74 | // At this point, the updated precached content has been fetched, 75 | // but the previous service worker will still serve the older 76 | // content until all client tabs are closed. 77 | console.log( 78 | 'New content is available and will be used when all ' + 79 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 80 | ); 81 | 82 | // Execute callback 83 | if (config && config.onUpdate) { 84 | config.onUpdate(registration); 85 | } 86 | } else { 87 | // At this point, everything has been precached. 88 | // It's the perfect time to display a 89 | // "Content is cached for offline use." message. 90 | console.log('Content is cached for offline use.'); 91 | 92 | // Execute callback 93 | if (config && config.onSuccess) { 94 | config.onSuccess(registration); 95 | } 96 | } 97 | } 98 | }; 99 | }; 100 | }) 101 | .catch(error => { 102 | console.error('Error during service worker registration:', error); 103 | }); 104 | } 105 | 106 | function checkValidServiceWorker(swUrl: string, config?: Config) { 107 | // Check if the service worker can be found. If it can't reload the page. 108 | fetch(swUrl, { 109 | headers: { 'Service-Worker': 'script' }, 110 | }) 111 | .then(response => { 112 | // Ensure service worker exists, and that we really are getting a JS file. 113 | const contentType = response.headers.get('content-type'); 114 | if ( 115 | response.status === 404 || 116 | (contentType != null && contentType.indexOf('javascript') === -1) 117 | ) { 118 | // No service worker found. Probably a different app. Reload the page. 119 | navigator.serviceWorker.ready.then(registration => { 120 | registration.unregister().then(() => { 121 | window.location.reload(); 122 | }); 123 | }); 124 | } else { 125 | // Service worker found. Proceed as normal. 126 | registerValidSW(swUrl, config); 127 | } 128 | }) 129 | .catch(() => { 130 | console.log( 131 | 'No internet connection found. App is running in offline mode.' 132 | ); 133 | }); 134 | } 135 | 136 | export function unregister() { 137 | if ('serviceWorker' in navigator) { 138 | navigator.serviceWorker.ready 139 | .then(registration => { 140 | registration.unregister(); 141 | }) 142 | .catch(error => { 143 | console.error(error.message); 144 | }); 145 | } 146 | } 147 | --------------------------------------------------------------------------------