├── .deploy ├── docker-compose.yml └── nginx-proxy-compose.yml ├── .dockerignore ├── .github └── workflows │ ├── README.md │ ├── build.yml │ └── release.yml ├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── MyApp.ServiceInterface ├── MyApp.ServiceInterface.csproj └── MyServices.cs ├── MyApp.ServiceModel ├── Hello.cs ├── MyApp.ServiceModel.csproj └── Types │ └── README.md ├── MyApp.Tests ├── IntegrationTest.cs ├── MyApp.Tests.csproj └── UnitTest.cs ├── MyApp.sln ├── MyApp ├── .gitignore ├── App_Data │ └── README.md ├── Configure.AppHost.cs ├── Configure.Auth.cs ├── Configure.AuthRepository.cs ├── Configure.Ui.cs ├── MyApp.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json ├── appsettings.json ├── images.d.ts ├── npm-shrinkwrap.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── manifest.json │ └── svg │ │ ├── app │ │ └── logo.svg │ │ └── svg-icons │ │ └── home.svg ├── scripts │ └── dev.js ├── src │ ├── App.tsx │ ├── app.css │ ├── components │ │ ├── About │ │ │ ├── about.css │ │ │ └── index.tsx │ │ ├── Admin │ │ │ └── index.tsx │ │ ├── Home │ │ │ ├── Hello.test.tsx │ │ │ ├── HelloApi.tsx │ │ │ ├── hello.css │ │ │ └── index.tsx │ │ ├── Profile.tsx │ │ ├── SignIn.tsx │ │ └── SignUp.tsx │ ├── index.tsx │ ├── logo.svg │ ├── react-app-env.d.ts │ ├── setupTests.ts │ ├── shared │ │ ├── dtos.ts │ │ └── index.tsx │ ├── sum.spec.ts │ └── sum.ts ├── tsconfig.json ├── tslint.json └── wwwroot │ └── index.html └── README.md /.deploy/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | services: 3 | app: 4 | image: ghcr.io/${IMAGE_REPO}:${RELEASE_VERSION} 5 | restart: always 6 | ports: 7 | - "8080" 8 | container_name: ${APP_NAME}_app 9 | environment: 10 | VIRTUAL_HOST: ${HOST_DOMAIN} 11 | VIRTUAL_PORT: 8080 # New default ASP.NET port -> https://learn.microsoft.com/en-us/dotnet/core/compatibility/containers/8.0/aspnet-port 12 | LETSENCRYPT_HOST: ${HOST_DOMAIN} 13 | LETSENCRYPT_EMAIL: ${LETSENCRYPT_EMAIL} 14 | volumes: 15 | - app-mydb:/app/App_Data 16 | 17 | networks: 18 | default: 19 | external: true 20 | name: nginx 21 | 22 | volumes: 23 | app-mydb: 24 | -------------------------------------------------------------------------------- /.deploy/nginx-proxy-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | 3 | services: 4 | nginx-proxy: 5 | image: nginxproxy/nginx-proxy 6 | container_name: nginx-proxy 7 | restart: always 8 | ports: 9 | - "80:80" 10 | - "443:443" 11 | volumes: 12 | - conf:/etc/nginx/conf.d 13 | - vhost:/etc/nginx/vhost.d 14 | - html:/usr/share/nginx/html 15 | - dhparam:/etc/nginx/dhparam 16 | - certs:/etc/nginx/certs:ro 17 | - /var/run/docker.sock:/tmp/docker.sock:ro 18 | labels: 19 | - "com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy" 20 | 21 | letsencrypt: 22 | image: nginxproxy/acme-companion:2.2 23 | container_name: nginx-proxy-le 24 | restart: always 25 | depends_on: 26 | - "nginx-proxy" 27 | environment: 28 | - DEFAULT_EMAIL=you@example.com 29 | volumes: 30 | - certs:/etc/nginx/certs:rw 31 | - acme:/etc/acme.sh 32 | - vhost:/etc/nginx/vhost.d 33 | - html:/usr/share/nginx/html 34 | - /var/run/docker.sock:/var/run/docker.sock:ro 35 | 36 | networks: 37 | default: 38 | name: nginx 39 | 40 | volumes: 41 | conf: 42 | vhost: 43 | html: 44 | dhparam: 45 | certs: 46 | acme: -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | */node_modules 2 | */npm-debug.log 3 | -------------------------------------------------------------------------------- /.github/workflows/README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | This template uses the deployment configurations for a ServiceStack .NET 8 application. The application is containerized using Docker and is set up to be automatically built and deployed via GitHub Actions. The recommended deployment target is a stand-alone Linux server running Ubuntu, with an NGINX reverse proxy also containerized using Docker, which a Docker Compose file is included in the template under the `.deploy` directory. 4 | 5 | ### Highlights 6 | - 🌐 **NGINX Reverse Proxy**: Utilizes an NGINX reverse proxy to handle web traffic and SSL termination. 7 | - 🚀 **GitHub Actions**: Leverages GitHub Actions for CI/CD, pushing Docker images to GitHub Container Registry and deploying them on a remote server. 8 | - 🐳 **Dockerized ServiceStack App**: The application is containerized, with the image built using `.NET 8`. 9 | - 🔄 **Automated Migrations**: Includes a separate service for running database migrations. 10 | 11 | ### Technology Stack 12 | - **Web Framework**: ServiceStack 13 | - **Language**: C# (.NET 8) 14 | - **Containerization**: Docker 15 | - **Reverse Proxy**: NGINX 16 | - **CI/CD**: GitHub Actions 17 | - **OS**: Ubuntu 22.04 (Deployment Server) 18 | 19 | 20 | 21 | ## Deployment Server Setup 22 | 23 | To successfully host your ServiceStack applications, there are several components you need to set up on your deployment server. This guide assumes you're working on a standalone Linux server (Ubuntu is recommended) with SSH access enabled. 24 | 25 | ### Prerequisites 26 | 27 | 1. **SSH Access**: Required for GitHub Actions to communicate with your server. 28 | 2. **Docker**: To containerize your application. 29 | 3. **Docker-Compose**: For orchestrating multiple containers. 30 | 4. **Ports**: 80 and 443 should be open for web access. 31 | 5. **nginx-reverse-proxy**: For routing traffic to multiple ServiceStack applications and managing TLS certificates. 32 | 33 | You can use any cloud-hosted or on-premises server like Digital Ocean, AWS, Azure, etc., for this setup. 34 | 35 | ### Step-by-Step Guide 36 | 37 | #### 1. Install Docker and Docker-Compose 38 | 39 | It is best to follow the [latest installation instructions on the Docker website](https://docs.docker.com/engine/install/ubuntu/) to ensure to have the correct setup with the latest patches. 40 | 41 | #### 2. Configure SSH for GitHub Actions 42 | 43 | Generate a dedicated SSH key pair to be used by GitHub Actions: 44 | 45 | ```bash 46 | ssh-keygen -t rsa -b 4096 -f ~/.ssh/github_actions 47 | ``` 48 | 49 | Add the public key to the `authorized_keys` file on your server: 50 | 51 | ```bash 52 | cat ~/.ssh/github_actions.pub >> ~/.ssh/authorized_keys 53 | ``` 54 | 55 | Then, add the *private* key to your GitHub Secrets as `DEPLOY_KEY` to enable GitHub Actions to SSH into the server securely. 56 | 57 | #### 3. Set Up nginx-reverse-proxy 58 | 59 | You should have a `docker-compose` file similar to the `nginx-proxy-compose.yml` in your repository. Upload this file to your server: 60 | 61 | ```bash 62 | scp nginx-proxy-compose.yml user@your_server:~/ 63 | ``` 64 | 65 | To bring up the nginx reverse proxy and its companion container for handling TLS certificates, run: 66 | 67 | ```bash 68 | docker compose -f ~/nginx-proxy-compose.yml up -d 69 | ``` 70 | 71 | This will start an nginx reverse proxy along with a companion container. They will automatically watch for additional Docker containers on the same network and initialize them with valid TLS certificates. 72 | 73 | 74 | 75 | ## GitHub Repository Setup 76 | 77 | Configuring your GitHub repository is an essential step for automating deployments via GitHub Actions. This guide assumes you have a `release.yml` workflow file in your repository's `.github/workflows/` directory, and your deployment server has been set up according to the [Deployment Server Setup](#Deployment-Server-Setup) guidelines. 78 | 79 | ### Secrets Configuration 80 | 81 | Your GitHub Actions workflow requires the following secrets to be set in your GitHub repository: 82 | 83 | 1. **`DEPLOY_HOST`**: The hostname for SSH access. This can be either an IP address or a domain with an A-record pointing to your server. 84 | 2. **`DEPLOY_USERNAME`**: The username for SSH login. Common examples include `ubuntu`, `ec2-user`, or `root`. 85 | 3. **`DEPLOY_KEY`**: The SSH private key to securely access the deployment server. This should be the same key you've set up on your server for GitHub Actions. 86 | 4. **`LETSENCRYPT_EMAIL`**: Your email address, required for Let's Encrypt automated TLS certificates. 87 | 88 | #### Using GitHub CLI for Secret Management 89 | 90 | You can conveniently set these secrets using the [GitHub CLI](https://cli.github.com/manual/gh_secret_set) like this: 91 | 92 | ```bash 93 | gh secret set DEPLOY_HOST --body="your-host-or-ip" 94 | gh secret set DEPLOY_USERNAME --body="your-username" 95 | gh secret set DEPLOY_KEY --bodyFile="path/to/your/ssh-private-key" 96 | gh secret set LETSENCRYPT_EMAIL --body="your-email@example.com" 97 | ``` 98 | 99 | These secrets will populate environment variables within your GitHub Actions workflow and other configuration files, enabling secure and automated deployment of your ServiceStack applications. 100 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | pull_request: {} 5 | push: 6 | branches: 7 | - '**' # matches every branch 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-22.04 12 | steps: 13 | - name: checkout 14 | uses: actions/checkout@v3 15 | 16 | - name: Setup dotnet 17 | uses: actions/setup-dotnet@v3 18 | with: 19 | dotnet-version: '8.0' 20 | 21 | - name: build 22 | run: dotnet build 23 | working-directory: . 24 | 25 | - name: test 26 | run: | 27 | dotnet test 28 | if [ $? -eq 0 ]; then 29 | echo TESTS PASSED 30 | else 31 | echo TESTS FAILED 32 | exit 1 33 | fi 34 | working-directory: ./MyApp.Tests 35 | 36 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | permissions: 3 | packages: write 4 | contents: write 5 | on: 6 | # Triggered on new GitHub Release 7 | release: 8 | types: [published] 9 | # Triggered on every successful Build action 10 | workflow_run: 11 | workflows: ["Build"] 12 | branches: [main,master] 13 | types: 14 | - completed 15 | # Manual trigger for rollback to specific release or redeploy latest 16 | workflow_dispatch: 17 | inputs: 18 | version: 19 | default: latest 20 | description: Tag you want to release. 21 | required: true 22 | 23 | jobs: 24 | push_to_registry: 25 | runs-on: ubuntu-22.04 26 | if: ${{ github.event.workflow_run.conclusion != 'failure' }} 27 | steps: 28 | # Checkout latest or specific tag 29 | - name: checkout 30 | if: ${{ github.event.inputs.version == '' || github.event.inputs.version == 'latest' }} 31 | uses: actions/checkout@v3 32 | - name: checkout tag 33 | if: ${{ github.event.inputs.version != '' && github.event.inputs.version != 'latest' }} 34 | uses: actions/checkout@v3 35 | with: 36 | ref: refs/tags/${{ github.event.inputs.version }} 37 | 38 | # Assign environment variables used in subsequent steps 39 | - name: Env variable assignment 40 | run: echo "image_repository_name=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV 41 | # TAG_NAME defaults to 'latest' if not a release or manual deployment 42 | - name: Assign version 43 | run: | 44 | echo "TAG_NAME=latest" >> $GITHUB_ENV 45 | if [ "${{ github.event.release.tag_name }}" != "" ]; then 46 | echo "TAG_NAME=${{ github.event.release.tag_name }}" >> $GITHUB_ENV 47 | fi; 48 | if [ "${{ github.event.inputs.version }}" != "" ]; then 49 | echo "TAG_NAME=${{ github.event.inputs.version }}" >> $GITHUB_ENV 50 | fi; 51 | if [ ! -z "${{ secrets.APPSETTINGS_PATCH }}" ]; then 52 | echo "HAS_APPSETTINGS_PATCH=true" >> $GITHUB_ENV 53 | else 54 | echo "HAS_APPSETTINGS_PATCH=false" >> $GITHUB_ENV 55 | fi; 56 | 57 | - name: Login to GitHub Container Registry 58 | uses: docker/login-action@v2 59 | with: 60 | registry: ghcr.io 61 | username: ${{ github.actor }} 62 | password: ${{ secrets.GITHUB_TOKEN }} 63 | 64 | 65 | - name: Setup dotnet 66 | uses: actions/setup-dotnet@v3 67 | with: 68 | dotnet-version: '8.0' 69 | 70 | - name: Install x tool 71 | if: env.HAS_APPSETTINGS_PATCH == 'true' 72 | run: dotnet tool install -g x 73 | 74 | - name: Apply Production AppSettings 75 | if: env.HAS_APPSETTINGS_PATCH == 'true' 76 | working-directory: ./MyApp 77 | run: | 78 | cat <> appsettings.json.patch 79 | ${{ secrets.APPSETTINGS_PATCH }} 80 | EOF 81 | x patch appsettings.json.patch 82 | 83 | 84 | # Build and push new docker image, skip for manual redeploy other than 'latest' 85 | - name: Build and push Docker image 86 | run: | 87 | dotnet publish --os linux --arch x64 -c Release -p:ContainerRepository=${{ env.image_repository_name }} -p:ContainerRegistry=ghcr.io -p:ContainerImageTags=${{ env.TAG_NAME }} -p:ContainerPort=80 88 | 89 | deploy_via_ssh: 90 | needs: push_to_registry 91 | runs-on: ubuntu-22.04 92 | if: ${{ github.event.workflow_run.conclusion != 'failure' }} 93 | steps: 94 | # Checkout latest or specific tag 95 | - name: checkout 96 | if: ${{ github.event.inputs.version == '' || github.event.inputs.version == 'latest' }} 97 | uses: actions/checkout@v3 98 | - name: checkout tag 99 | if: ${{ github.event.inputs.version != '' && github.event.inputs.version != 'latest' }} 100 | uses: actions/checkout@v3 101 | with: 102 | ref: refs/tags/${{ github.event.inputs.version }} 103 | 104 | - name: repository name fix and env 105 | run: | 106 | echo "image_repository_name=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV 107 | echo "TAG_NAME=latest" >> $GITHUB_ENV 108 | if [ "${{ github.event.release.tag_name }}" != "" ]; then 109 | echo "TAG_NAME=${{ github.event.release.tag_name }}" >> $GITHUB_ENV 110 | fi; 111 | if [ "${{ github.event.inputs.version }}" != "" ]; then 112 | echo "TAG_NAME=${{ github.event.inputs.version }}" >> $GITHUB_ENV 113 | fi; 114 | 115 | - name: Create .env file 116 | run: | 117 | echo "Generating .env file" 118 | 119 | echo "# Autogenerated .env file" > .deploy/.env 120 | echo "HOST_DOMAIN=${{ secrets.DEPLOY_HOST }}" >> .deploy/.env 121 | echo "LETSENCRYPT_EMAIL=${{ secrets.LETSENCRYPT_EMAIL }}" >> .deploy/.env 122 | echo "APP_NAME=${{ github.event.repository.name }}" >> .deploy/.env 123 | echo "IMAGE_REPO=${{ env.image_repository_name }}" >> .deploy/.env 124 | echo "RELEASE_VERSION=${{ env.TAG_NAME }}" >> .deploy/.env 125 | 126 | # Copy only the docker-compose.yml to remote server home folder 127 | - name: copy files to target server via scp 128 | uses: appleboy/scp-action@v0.1.3 129 | with: 130 | host: ${{ secrets.DEPLOY_HOST }} 131 | username: ${{ secrets.DEPLOY_USERNAME }} 132 | port: 22 133 | key: ${{ secrets.DEPLOY_KEY }} 134 | strip_components: 2 135 | source: "./.deploy/docker-compose.yml,./.deploy/.env" 136 | target: "~/.deploy/${{ github.event.repository.name }}/" 137 | 138 | - name: Setup App_Data volume directory 139 | uses: appleboy/ssh-action@v0.1.5 140 | env: 141 | APPTOKEN: ${{ secrets.GITHUB_TOKEN }} 142 | USERNAME: ${{ secrets.DEPLOY_USERNAME }} 143 | with: 144 | host: ${{ secrets.DEPLOY_HOST }} 145 | username: ${{ secrets.DEPLOY_USERNAME }} 146 | key: ${{ secrets.DEPLOY_KEY }} 147 | port: 22 148 | envs: APPTOKEN,USERNAME 149 | script: | 150 | set -e 151 | echo $APPTOKEN | docker login ghcr.io -u $USERNAME --password-stdin 152 | cd ~/.deploy/${{ github.event.repository.name }} 153 | docker compose pull 154 | export APP_ID=$(docker compose run --entrypoint "id -u" --rm app) 155 | docker compose run --entrypoint "chown $APP_ID:$APP_ID /app/App_Data" --user root --rm app 156 | 157 | # Deploy Docker image with your application using `docker compose up` remotely 158 | - name: remote docker-compose up via ssh 159 | uses: appleboy/ssh-action@v0.1.5 160 | env: 161 | APPTOKEN: ${{ secrets.GITHUB_TOKEN }} 162 | USERNAME: ${{ secrets.DEPLOY_USERNAME }} 163 | with: 164 | host: ${{ secrets.DEPLOY_HOST }} 165 | username: ${{ secrets.DEPLOY_USERNAME }} 166 | key: ${{ secrets.DEPLOY_KEY }} 167 | port: 22 168 | envs: APPTOKEN,USERNAME 169 | script: | 170 | echo $APPTOKEN | docker login ghcr.io -u $USERNAME --password-stdin 171 | cd ~/.deploy/${{ github.event.repository.name }} 172 | docker compose pull 173 | docker compose up app -d 174 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # Custom 7 | dist/ 8 | wwwroot/ 9 | coverage/ 10 | 11 | # User-specific files 12 | *.suo 13 | *.user 14 | *.userosscache 15 | *.sln.docstates 16 | 17 | # User-specific files (MonoDevelop/Xamarin Studio) 18 | *.userprefs 19 | 20 | # Build results 21 | [Dd]ebug/ 22 | [Dd]ebugPublic/ 23 | [Rr]elease/ 24 | [Rr]eleases/ 25 | x64/ 26 | x86/ 27 | bld/ 28 | [Bb]in/ 29 | [Oo]bj/ 30 | [Ll]og/ 31 | 32 | # Visual Studio 2015 cache/options directory 33 | .vs/ 34 | # Uncomment if you have tasks that create the project's static files in wwwroot 35 | #wwwroot/ 36 | 37 | # MSTest test Results 38 | [Tt]est[Rr]esult*/ 39 | [Bb]uild[Ll]og.* 40 | 41 | # NUNIT 42 | *.VisualState.xml 43 | TestResult.xml 44 | 45 | # Build Results of an ATL Project 46 | [Dd]ebugPS/ 47 | [Rr]eleasePS/ 48 | dlldata.c 49 | 50 | # .NET Core 51 | project.lock.json 52 | project.fragment.lock.json 53 | artifacts/ 54 | #**/Properties/launchSettings.json 55 | 56 | *_i.c 57 | *_p.c 58 | *_i.h 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.svclog 79 | *.scc 80 | 81 | # Chutzpah Test files 82 | _Chutzpah* 83 | 84 | # Visual C++ cache files 85 | ipch/ 86 | *.aps 87 | *.ncb 88 | *.opendb 89 | *.opensdf 90 | *.sdf 91 | *.cachefile 92 | *.VC.db 93 | *.VC.VC.opendb 94 | 95 | # Visual Studio profiler 96 | *.psess 97 | *.vsp 98 | *.vspx 99 | *.sap 100 | 101 | # TFS 2012 Local Workspace 102 | $tf/ 103 | 104 | # Guidance Automation Toolkit 105 | *.gpState 106 | 107 | # ReSharper is a .NET coding add-in 108 | _ReSharper*/ 109 | *.[Rr]e[Ss]harper 110 | *.DotSettings.user 111 | 112 | # JustCode is a .NET coding add-in 113 | .JustCode 114 | 115 | # TeamCity is a build add-in 116 | _TeamCity* 117 | 118 | # DotCover is a Code Coverage Tool 119 | *.dotCover 120 | 121 | # Visual Studio code coverage results 122 | *.coverage 123 | *.coveragexml 124 | 125 | # NCrunch 126 | _NCrunch_* 127 | .*crunch*.local.xml 128 | nCrunchTemp_* 129 | 130 | # MightyMoose 131 | *.mm.* 132 | AutoTest.Net/ 133 | 134 | # Web workbench (sass) 135 | .sass-cache/ 136 | 137 | # Installshield output folder 138 | [Ee]xpress/ 139 | 140 | # DocProject is a documentation generator add-in 141 | DocProject/buildhelp/ 142 | DocProject/Help/*.HxT 143 | DocProject/Help/*.HxC 144 | DocProject/Help/*.hhc 145 | DocProject/Help/*.hhk 146 | DocProject/Help/*.hhp 147 | DocProject/Help/Html2 148 | DocProject/Help/html 149 | 150 | # Click-Once directory 151 | publish/ 152 | 153 | # Publish Web Output 154 | *.[Pp]ublish.xml 155 | *.azurePubxml 156 | # TODO: Comment the next line if you want to checkin your web deploy settings 157 | # but database connection strings (with potential passwords) will be unencrypted 158 | *.pubxml 159 | *.publishproj 160 | 161 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 162 | # checkin your Azure Web App publish settings, but sensitive information contained 163 | # in these scripts will be unencrypted 164 | PublishScripts/ 165 | 166 | # NuGet Packages 167 | *.nupkg 168 | # The packages folder can be ignored because of Package Restore 169 | **/packages/* 170 | # except build/, which is used as an MSBuild target. 171 | !**/packages/build/ 172 | # Uncomment if necessary however generally it will be regenerated when needed 173 | #!**/packages/repositories.config 174 | # NuGet v3's project.json files produces more ignorable files 175 | *.nuget.props 176 | *.nuget.targets 177 | 178 | # Microsoft Azure Build Output 179 | csx/ 180 | *.build.csdef 181 | 182 | # Microsoft Azure Emulator 183 | ecf/ 184 | rcf/ 185 | 186 | # Windows Store app package directories and files 187 | AppPackages/ 188 | BundleArtifacts/ 189 | Package.StoreAssociation.xml 190 | _pkginfo.txt 191 | 192 | # Visual Studio cache files 193 | # files ending in .cache can be ignored 194 | *.[Cc]ache 195 | # but keep track of directories ending in .cache 196 | !*.[Cc]ache/ 197 | 198 | # Others 199 | ClientBin/ 200 | ~$* 201 | *~ 202 | *.dbmdl 203 | *.dbproj.schemaview 204 | *.jfm 205 | *.pfx 206 | *.publishsettings 207 | orleans.codegen.cs 208 | 209 | # Since there are multiple workflows, uncomment next line to ignore bower_components 210 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 211 | #bower_components/ 212 | 213 | # RIA/Silverlight projects 214 | Generated_Code/ 215 | 216 | # Backup & report files from converting an old project file 217 | # to a newer Visual Studio version. Backup files are not needed, 218 | # because we have git ;-) 219 | _UpgradeReport_Files/ 220 | Backup*/ 221 | UpgradeLog*.XML 222 | UpgradeLog*.htm 223 | 224 | # SQL Server files 225 | *.mdf 226 | *.ldf 227 | *.ndf 228 | 229 | # Business Intelligence projects 230 | *.rdl.data 231 | *.bim.layout 232 | *.bim_*.settings 233 | 234 | # Microsoft Fakes 235 | FakesAssemblies/ 236 | 237 | # GhostDoc plugin setting file 238 | *.GhostDoc.xml 239 | 240 | # Node.js Tools for Visual Studio 241 | .ntvs_analysis.dat 242 | node_modules/ 243 | 244 | # Typescript v1 declaration files 245 | typings/ 246 | 247 | # Visual Studio 6 build log 248 | *.plg 249 | 250 | # Visual Studio 6 workspace options file 251 | *.opt 252 | 253 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 254 | *.vbw 255 | 256 | # Visual Studio LightSwitch build output 257 | **/*.HTMLClient/GeneratedArtifacts 258 | **/*.DesktopClient/GeneratedArtifacts 259 | **/*.DesktopClient/ModelManifest.xml 260 | **/*.Server/GeneratedArtifacts 261 | **/*.Server/ModelManifest.xml 262 | _Pvt_Extensions 263 | 264 | # Paket dependency manager 265 | .paket/paket.exe 266 | paket-files/ 267 | 268 | # FAKE - F# Make 269 | .fake/ 270 | 271 | # JetBrains Rider 272 | .idea/ 273 | *.sln.iml 274 | 275 | # CodeRush 276 | .cr/ 277 | 278 | # Python Tools for Visual Studio (PTVS) 279 | __pycache__/ 280 | *.pyc 281 | 282 | # Cake - Uncomment if you are using it 283 | # tools/** 284 | # !tools/packages.config 285 | 286 | # Telerik's JustMock configuration file 287 | *.jmconfig 288 | 289 | # BizTalk build output 290 | *.btp.cs 291 | *.btm.cs 292 | *.odx.cs 293 | *.xsd.cs 294 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/MyApp/bin/Debug/net6.0/MyApp.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}/MyApp", 15 | "stopAtEntry": false, 16 | "serverReadyAction": { 17 | "action": "openExternally", 18 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)" 19 | }, 20 | "env": { 21 | "ASPNETCORE_ENVIRONMENT": "Development" 22 | }, 23 | "sourceFileMap": { 24 | "/Views": "${workspaceFolder}/Views" 25 | } 26 | }, 27 | { 28 | "name": ".NET Core Attach", 29 | "type": "coreclr", 30 | "request": "attach" 31 | } 32 | ] 33 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "build", 8 | "command": "dotnet build", 9 | "type": "shell", 10 | "group": "build", 11 | "presentation": { 12 | "reveal": "silent" 13 | }, 14 | "problemMatcher": "$msCompile" 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /MyApp.ServiceInterface/MyApp.ServiceInterface.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /MyApp.ServiceInterface/MyServices.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ServiceStack; 3 | using MyApp.ServiceModel; 4 | 5 | namespace MyApp.ServiceInterface 6 | { 7 | public class MyServices : Service 8 | { 9 | public object Any(Hello request) 10 | { 11 | return new HelloResponse { Result = $"Hello, {request.Name}!" }; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /MyApp.ServiceModel/Hello.cs: -------------------------------------------------------------------------------- 1 | using ServiceStack; 2 | 3 | namespace MyApp.ServiceModel 4 | { 5 | [Route("/hello")] 6 | [Route("/hello/{Name}")] 7 | public class Hello : IReturn 8 | { 9 | public string Name { get; set; } 10 | } 11 | 12 | public class HelloResponse 13 | { 14 | public string Result { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /MyApp.ServiceModel/MyApp.ServiceModel.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /MyApp.ServiceModel/Types/README.md: -------------------------------------------------------------------------------- 1 | As part of our [Physical Project Structure](https://docs.servicestack.net/physical-project-structure) convention we recommend maintaining any shared non Request/Response DTOs in the `ServiceModel.Types` namespace. -------------------------------------------------------------------------------- /MyApp.Tests/IntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using Funq; 2 | using ServiceStack; 3 | using NUnit.Framework; 4 | using MyApp.ServiceInterface; 5 | using MyApp.ServiceModel; 6 | 7 | namespace MyApp.Tests; 8 | 9 | public class IntegrationTest 10 | { 11 | const string BaseUri = "http://localhost:2000/"; 12 | private readonly ServiceStackHost appHost; 13 | 14 | class AppHost : AppSelfHostBase 15 | { 16 | public AppHost() : base(nameof(IntegrationTest), typeof(MyServices).Assembly) { } 17 | 18 | public override void Configure(Container container) 19 | { 20 | } 21 | } 22 | 23 | public IntegrationTest() 24 | { 25 | appHost = new AppHost() 26 | .Init() 27 | .Start(BaseUri); 28 | } 29 | 30 | [OneTimeTearDown] 31 | public void OneTimeTearDown() => appHost.Dispose(); 32 | 33 | public IServiceClient CreateClient() => new JsonServiceClient(BaseUri); 34 | 35 | [Test] 36 | public void Can_call_Hello_Service() 37 | { 38 | var client = CreateClient(); 39 | 40 | var response = client.Get(new Hello { Name = "World" }); 41 | 42 | Assert.That(response.Result, Is.EqualTo("Hello, World!")); 43 | } 44 | } -------------------------------------------------------------------------------- /MyApp.Tests/MyApp.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | portable 6 | Library 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /MyApp.Tests/UnitTest.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using ServiceStack; 3 | using ServiceStack.Testing; 4 | using MyApp.ServiceInterface; 5 | using MyApp.ServiceModel; 6 | 7 | namespace MyApp.Tests; 8 | 9 | public class UnitTest 10 | { 11 | private readonly ServiceStackHost appHost; 12 | 13 | public UnitTest() 14 | { 15 | appHost = new BasicAppHost().Init(); 16 | appHost.Container.AddTransient(); 17 | } 18 | 19 | [OneTimeTearDown] 20 | public void OneTimeTearDown() => appHost.Dispose(); 21 | 22 | [Test] 23 | public void Can_call_MyServices() 24 | { 25 | var service = appHost.Container.Resolve(); 26 | 27 | var response = (HelloResponse)service.Any(new Hello { Name = "World" }); 28 | 29 | Assert.That(response.Result, Is.EqualTo("Hello, World!")); 30 | } 31 | } -------------------------------------------------------------------------------- /MyApp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.3 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyApp", "MyApp\MyApp.csproj", "{5F817400-1A3A-48DF-98A6-E7E5A3DC762F}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyApp.ServiceInterface", "MyApp.ServiceInterface\MyApp.ServiceInterface.csproj", "{5B8FFF01-1E0B-477D-9D7F-93016C128B23}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyApp.ServiceModel", "MyApp.ServiceModel\MyApp.ServiceModel.csproj", "{0127B6CA-1B79-46A6-8307-B36836D107F0}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyApp.Tests", "MyApp.Tests\MyApp.Tests.csproj", "{455EC1EF-134F-4CD4-9C78-E813E4E6D8F6}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {5B8FFF01-1E0B-477D-9D7F-93016C128B23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {5B8FFF01-1E0B-477D-9D7F-93016C128B23}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {5B8FFF01-1E0B-477D-9D7F-93016C128B23}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {5B8FFF01-1E0B-477D-9D7F-93016C128B23}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {0127B6CA-1B79-46A6-8307-B36836D107F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {0127B6CA-1B79-46A6-8307-B36836D107F0}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {0127B6CA-1B79-46A6-8307-B36836D107F0}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {0127B6CA-1B79-46A6-8307-B36836D107F0}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {455EC1EF-134F-4CD4-9C78-E813E4E6D8F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {455EC1EF-134F-4CD4-9C78-E813E4E6D8F6}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {455EC1EF-134F-4CD4-9C78-E813E4E6D8F6}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {455EC1EF-134F-4CD4-9C78-E813E4E6D8F6}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {02854F2A-8EF4-468E-80A3-CD64BBAF5D15} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /MyApp/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /MyApp/App_Data/README.md: -------------------------------------------------------------------------------- 1 | ## App Writable Folder 2 | 3 | This directory is designated for: 4 | 5 | - **Embedded Databases**: Such as SQLite. 6 | - **Writable Files**: Files that the application might need to modify during its operation. 7 | 8 | For applications running in **Docker**, it's a common practice to mount this directory as an external volume. This ensures: 9 | 10 | - **Data Persistence**: App data is preserved across deployments. 11 | - **Easy Replication**: Facilitates seamless data replication for backup or migration purposes. 12 | -------------------------------------------------------------------------------- /MyApp/Configure.AppHost.cs: -------------------------------------------------------------------------------- 1 | using Funq; 2 | using ServiceStack; 3 | using MyApp.ServiceInterface; 4 | 5 | [assembly: HostingStartup(typeof(MyApp.AppHost))] 6 | 7 | namespace MyApp; 8 | 9 | public class AppHost : AppHostBase, IHostingStartup 10 | { 11 | public void Configure(IWebHostBuilder builder) => builder 12 | .ConfigureServices(services => { 13 | // Configure ASP.NET Core IOC Dependencies 14 | }); 15 | 16 | public AppHost() : base("MyApp", typeof(MyServices).Assembly) {} 17 | 18 | public override void Configure(Container container) 19 | { 20 | // enable server-side rendering, see: https://sharpscript.net/docs/sharp-pages 21 | Plugins.Add(new SharpPagesFeature { 22 | EnableSpaFallback = true 23 | }); 24 | 25 | SetConfig(new HostConfig 26 | { 27 | AddRedirectParamsToQueryString = true, 28 | }); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /MyApp/Configure.Auth.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using ServiceStack; 3 | using ServiceStack.Auth; 4 | using ServiceStack.FluentValidation; 5 | 6 | [assembly: HostingStartup(typeof(MyApp.ConfigureAuth))] 7 | 8 | namespace MyApp 9 | { 10 | // Add any additional metadata properties you want to store in the Users Typed Session 11 | public class CustomUserSession : AuthUserSession 12 | { 13 | } 14 | 15 | // Custom Validator to add custom validators to built-in /register Service requiring DisplayName and ConfirmPassword 16 | public class CustomRegistrationValidator : RegistrationValidator 17 | { 18 | public CustomRegistrationValidator() 19 | { 20 | RuleSet(ApplyTo.Post, () => 21 | { 22 | RuleFor(x => x.DisplayName).NotEmpty(); 23 | RuleFor(x => x.ConfirmPassword).NotEmpty(); 24 | }); 25 | } 26 | } 27 | 28 | public class ConfigureAuth : IHostingStartup 29 | { 30 | public void Configure(IWebHostBuilder builder) => builder 31 | .ConfigureServices(services => { 32 | //services.AddSingleton(new MemoryCacheClient()); //Store User Sessions in Memory Cache (default) 33 | }) 34 | .ConfigureAppHost(appHost => { 35 | var appSettings = appHost.AppSettings; 36 | appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(), 37 | new IAuthProvider[] { 38 | new CredentialsAuthProvider(appSettings), /* Sign In with Username / Password credentials */ 39 | new FacebookAuthProvider(appSettings), /* Create App https://developers.facebook.com/apps */ 40 | new GoogleAuthProvider(appSettings), /* Create App https://console.developers.google.com/apis/credentials */ 41 | new MicrosoftGraphAuthProvider(appSettings), /* Create App https://apps.dev.microsoft.com */ 42 | })); 43 | 44 | appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service 45 | 46 | //override the default registration validation with your own custom implementation 47 | appHost.RegisterAs>(); 48 | }); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /MyApp/Configure.AuthRepository.cs: -------------------------------------------------------------------------------- 1 | using ServiceStack; 2 | using ServiceStack.Web; 3 | using ServiceStack.Auth; 4 | using ServiceStack.Configuration; 5 | 6 | [assembly: HostingStartup(typeof(MyApp.ConfigureAuthRepository))] 7 | 8 | namespace MyApp 9 | { 10 | // Custom User Table with extended Metadata properties 11 | public class AppUser : UserAuth 12 | { 13 | public string? ProfileUrl { get; set; } 14 | public string? LastLoginIp { get; set; } 15 | public DateTime? LastLoginDate { get; set; } 16 | } 17 | 18 | public class AppUserAuthEvents : AuthEvents 19 | { 20 | public override void OnAuthenticated(IRequest req, IAuthSession session, IServiceBase authService, 21 | IAuthTokens tokens, Dictionary authInfo) 22 | { 23 | var authRepo = HostContext.AppHost.GetAuthRepository(req); 24 | using (authRepo as IDisposable) 25 | { 26 | var userAuth = (AppUser)authRepo.GetUserAuth(session.UserAuthId); 27 | userAuth.ProfileUrl = session.GetProfileUrl(); 28 | userAuth.LastLoginIp = req.UserHostAddress; 29 | userAuth.LastLoginDate = DateTime.UtcNow; 30 | authRepo.SaveUserAuth(userAuth); 31 | } 32 | } 33 | } 34 | 35 | public class ConfigureAuthRepository : IHostingStartup 36 | { 37 | public void Configure(IWebHostBuilder builder) => builder 38 | .ConfigureServices(services => services.AddSingleton(c => 39 | new InMemoryAuthRepository())) 40 | .ConfigureAppHost(appHost => { 41 | var authRepo = appHost.Resolve(); 42 | authRepo.InitSchema(); 43 | // CreateUser(authRepo, "admin@email.com", "Admin User", "p@55wOrd", roles:new[]{ RoleNames.Admin }); 44 | }, afterConfigure: appHost => 45 | appHost.AssertPlugin().AuthEvents.Add(new AppUserAuthEvents())); 46 | 47 | // Add initial Users to the configured Auth Repository 48 | public void CreateUser(IAuthRepository authRepo, string email, string name, string password, string[] roles) 49 | { 50 | if (authRepo.GetUserAuthByUserName(email) == null) 51 | { 52 | var newAdmin = new AppUser { Email = email, DisplayName = name }; 53 | var user = authRepo.CreateUserAuth(newAdmin, password); 54 | authRepo.AssignRoles(user, roles); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /MyApp/Configure.Ui.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using ServiceStack; 3 | 4 | [assembly: HostingStartup(typeof(MyApp.ConfigureUi))] 5 | 6 | namespace MyApp; 7 | 8 | public class ConfigureUi : IHostingStartup 9 | { 10 | public void Configure(IWebHostBuilder builder) => builder 11 | .ConfigureAppHost(appHost => { 12 | // if wwwroot/ is empty, build Client App with 'npm run build' 13 | var svgDir = appHost.RootDirectory.GetDirectory("/svg") ?? appHost.ContentRootDirectory.GetDirectory("/public/svg"); 14 | if (svgDir != null) 15 | { 16 | Svg.Load(svgDir); 17 | } 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /MyApp/MyApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | DefaultContainer 5 | net8.0 6 | enable 7 | enable 8 | latest 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /MyApp/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | var app = builder.Build(); 4 | 5 | // Configure the HTTP request pipeline. 6 | if (!app.Environment.IsDevelopment()) 7 | { 8 | app.UseExceptionHandler("/Error"); 9 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 10 | app.UseHsts(); 11 | app.UseHttpsRedirection(); 12 | } 13 | app.UseServiceStack(new AppHost()); 14 | 15 | app.Run(); -------------------------------------------------------------------------------- /MyApp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "https://localhost:5001/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "MyApp": { 12 | "commandName": "Project", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | }, 17 | "applicationUrl": "https://localhost:5001/" 18 | }, 19 | "IIS Express": { 20 | "commandName": "IISExpress", 21 | "launchBrowser": true, 22 | "environmentVariables": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /MyApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "DetailedErrors": true, 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Information", 6 | "Microsoft.AspNetCore": "Warning" 7 | } 8 | }, 9 | "oauth.RedirectUrl": "https://localhost:5001/", 10 | "oauth.CallbackUrl": "https://localhost:5001/auth/{0}", 11 | "oauth.facebook.Permissions": [ "email", "user_location" ], 12 | "oauth.facebook.AppId": "531608123577340", 13 | "oauth.facebook.AppSecret": "9e1e6591a7f15cbc1b305729f4b14c0b", 14 | "oauth.google.ConsumerKey": "274592649256-nmvuiu5ri7s1nghilbo6nmfd6h8j71sc.apps.googleusercontent.com", 15 | "oauth.google.ConsumerSecret": "aKOJngvq0USp3kyA_mkFH8Il", 16 | "oauth.microsoftgraph.AppId": "8208d98e-400d-4ce9-89ba-d92610c67e13", 17 | "oauth.microsoftgraph.AppSecret": "hsrMP46|_kfkcYCWSW516?%", 18 | "oauth.microsoftgraph.SavePhoto": "true", 19 | "oauth.microsoftgraph.SavePhotoSize": "96x96" 20 | } 21 | -------------------------------------------------------------------------------- /MyApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "NavItems": [ 10 | { "href":"/", "label": "Home", "exact":true }, 11 | { "href":"/about", "label": "About" }, 12 | { "href":"/signin", "label": "Sign In", "hide":"auth" }, 13 | { "href":"/profile", "label": "Profile", "show":"auth" }, 14 | { "href":"/admin", "label": "Admin", "show":"role:Admin" } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /MyApp/images.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.svg' 2 | declare module '*.png' 3 | declare module '*.jpg' 4 | -------------------------------------------------------------------------------- /MyApp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "postinstall": "npm run build", 7 | "dev": "rimraf wwwroot/ && node scripts/dev.js", 8 | "start": "react-scripts start", 9 | "dtos": "x typescript", 10 | "build": "rimraf wwwroot/ && react-scripts build && (move build wwwroot || mv build wwwroot)", 11 | "publish": "npm run build && dotnet publish -c Release", 12 | "test": "react-scripts test --env=jsdom --watchAll", 13 | "test-coverage": "npm test -- --coverage", 14 | "eject": "react-scripts eject" 15 | }, 16 | "proxy": "https://localhost:5001/", 17 | "dependencies": { 18 | "@servicestack/client": "^1.1.19", 19 | "@servicestack/react": "^1.0.8", 20 | "@testing-library/jest-dom": "^5.12.0", 21 | "@testing-library/react": "^11.2.7", 22 | "@testing-library/user-event": "^12.8.3", 23 | "@types/jest": "^26.0.23", 24 | "@types/node": "^12.20.13", 25 | "@types/react": "^17.0.6", 26 | "@types/react-dom": "^17.0.5", 27 | "@types/react-router-dom": "^5.1.7", 28 | "bootstrap": "^5.0.1", 29 | "cross-fetch": "^3.1.4", 30 | "react": "^17.0.2", 31 | "react-dom": "^17.0.2", 32 | "react-router-dom": "^5.2.0", 33 | "react-scripts": "^4.0.3", 34 | "typescript": "^4.5.4", 35 | "web-vitals": "^1.1.2" 36 | }, 37 | "eslintConfig": { 38 | "extends": [ 39 | "react-app", 40 | "react-app/jest" 41 | ] 42 | }, 43 | "browserslist": { 44 | "production": [ 45 | ">0.2%", 46 | "not dead", 47 | "not op_mini all" 48 | ], 49 | "development": [ 50 | "last 1 chrome version", 51 | "last 1 firefox version", 52 | "last 1 safari version" 53 | ] 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MyApp/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LegacyTemplates/react-spa/5d86a8afdca33286573f0e3219ed459f6d1e9e29/MyApp/public/favicon.ico -------------------------------------------------------------------------------- /MyApp/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | 22 | React App 23 | 24 | 25 | 26 | 35 | 36 | 39 |
40 | 50 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /MyApp/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "MyApp", 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 | -------------------------------------------------------------------------------- /MyApp/public/svg/app/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /MyApp/public/svg/svg-icons/home.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MyApp/scripts/dev.js: -------------------------------------------------------------------------------- 1 | // https://github.com/facebook/create-react-app/issues/1070#issuecomment-314696847 2 | process.env.NODE_ENV = 'development'; 3 | 4 | const fs = require('fs-extra'); 5 | const paths = require('react-scripts/config/paths'); 6 | 7 | const path = require('path'); 8 | const appDirectory = fs.realpathSync(process.cwd()); 9 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 10 | 11 | const webpack = require('webpack'); 12 | const config = require('react-scripts/config/webpack.config.js')('development'); 13 | console.log(config) 14 | 15 | // remove react-dev-utils/webpackHotDevClient.js 16 | // config.entry.splice(config.entry.findIndex( 17 | // e => e.indexOf('webpackHotDevClient.js') >= 0), 1); 18 | 19 | config.output.path = resolveApp('wwwroot'); 20 | 21 | webpack(config).watch({}, (err, stats) => { 22 | if (err) { 23 | console.error(err); 24 | } else { 25 | //copyPublicFolder(); 26 | } 27 | console.error(stats.toString({ 28 | chunks: false, 29 | colors: true 30 | })); 31 | }); 32 | 33 | function copyPublicFolder() { 34 | fs.copySync(paths.appPublic, paths.appBuild, { 35 | dereference: true, 36 | filter: file => file !== paths.appHtml 37 | }); 38 | } -------------------------------------------------------------------------------- /MyApp/src/App.tsx: -------------------------------------------------------------------------------- 1 | import 'es6-shim'; 2 | import * as React from 'react'; 3 | 4 | import { BrowserRouter as Router, Route, Link, Switch, Redirect } from 'react-router-dom'; 5 | import { Routes, Roles, StateContext } from './shared'; 6 | import { Navbar, Fallback, Forbidden } from '@servicestack/react'; 7 | 8 | import { Home } from './components/Home'; 9 | import { About } from './components/About'; 10 | import { SignIn } from './components/SignIn'; 11 | import { SignUp } from './components/SignUp'; 12 | import { Profile } from './components/Profile'; 13 | import { Admin } from './components/Admin'; 14 | 15 | export const App: React.FC = () => { 16 | const { state } = React.useContext(StateContext); 17 | 18 | const renderHome = () => ; 19 | const renderAbout = () => ; 20 | 21 | const requiresAuth = (Component:any, path?:string) => { 22 | if (!state.userSession) { 23 | return () => = (props:any) => ( 4 |
5 |
6 |

{props.message}

7 |
8 | ); 9 | -------------------------------------------------------------------------------- /MyApp/src/components/Admin/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StateContext } from '../../shared'; 3 | 4 | export const Admin: React.FC = () => { 5 | 6 | const { state } = React.useContext(StateContext); 7 | const user = state.userSession!; 8 | const roles = user && user.roles; 9 | 10 | return ( 11 |
12 |
13 |

14 | {user.displayName} 15 |

16 |

17 | {user.userName} 18 |

19 |

20 | {roles && roles.map(x => {x})} 21 |

22 |

Admin Page

23 |
24 | ); 25 | } 26 | -------------------------------------------------------------------------------- /MyApp/src/components/Home/Hello.test.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { render, screen } from '@testing-library/react'; 4 | import userEvent from '@testing-library/user-event'; 5 | 6 | import { HelloApi } from './HelloApi'; 7 | 8 | describe('', () => { 9 | 10 | it ('Updates heading on input change', done => { 11 | 12 | const el = render(); 13 | 14 | expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent(''); 15 | 16 | let input = el.container.querySelector('#txtName')!; 17 | userEvent.type(input, 'A'); 18 | 19 | setTimeout(() => { 20 | expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent('Hello, A!'); 21 | done(); 22 | }, 100); 23 | }); 24 | 25 | }); 26 | -------------------------------------------------------------------------------- /MyApp/src/components/Home/HelloApi.tsx: -------------------------------------------------------------------------------- 1 | import './hello.css'; 2 | 3 | import * as React from 'react'; 4 | import { Input } from '@servicestack/react'; 5 | import { client } from '../../shared'; 6 | import { Hello } from '../../shared/dtos'; 7 | 8 | export interface HelloApiProps { 9 | name: string; 10 | } 11 | 12 | export const HelloApi: React.FC = (props:HelloApiProps) => { 13 | const [name, setName] = React.useState(props.name); 14 | const [result, setResult] = React.useState(''); 15 | 16 | React.useEffect(() => { 17 | (async () => { 18 | setResult(!name ? '' : (await client.get(new Hello({ name }) )).result) 19 | })(); 20 | }, [name]); // fires when name changes 21 | 22 | return (
23 |
24 | 25 |

{ result }

26 |
27 |
); 28 | } 29 | -------------------------------------------------------------------------------- /MyApp/src/components/Home/hello.css: -------------------------------------------------------------------------------- 1 | .result { 2 | margin: 10px; 3 | color: #0097b3; 4 | } 5 | -------------------------------------------------------------------------------- /MyApp/src/components/Home/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StateContext, signout } from '../../shared'; 3 | import { LinkButton } from '@servicestack/react'; 4 | import { HelloApi } from './HelloApi'; 5 | 6 | export const Home: React.FC = (props:any) => { 7 | const {state, dispatch} = React.useContext(StateContext); 8 | 9 | const handleSignOut = async () => await signout(dispatch); 10 | 11 | return (
12 |
13 | 14 |
15 |
16 | 17 |
18 |
19 |
20 | {state.userSession ? 21 | (
22 |

{`Hi ${state.userSession!.displayName}!`}

23 | Sign Out 24 |
) : 25 | (
26 |

You are not authenticated.

27 | Sign In 28 | Register New User 29 |
)} 30 |
31 |
); 32 | } -------------------------------------------------------------------------------- /MyApp/src/components/Profile.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StateContext, signout } from '../shared'; 3 | import { LinkButton } from '@servicestack/react'; 4 | 5 | export const Profile: React.FC = () => { 6 | 7 | const { state, dispatch } = React.useContext(StateContext); 8 | const user = state.userSession!; 9 | const roles = user && user.roles; 10 | const permissions = user && user.permissions; 11 | 12 | const handleSignOut = async () => await signout(dispatch); 13 | 14 | return ( 15 |
16 | 17 | Profile 18 | 19 |

20 | {user.displayName} {user.userId ? #{user.userId} : null} 21 |

22 |

23 | {user.userName} 24 |

25 |

26 | {roles && roles.map(x => {x})} 27 |

28 |

29 | {permissions && permissions.map(x => {x})} 30 |

31 |

32 | Sign Out 33 |

34 |
35 | ); 36 | } 37 | -------------------------------------------------------------------------------- /MyApp/src/components/SignIn.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { useState, useContext } from 'react'; 3 | import { ErrorSummary, Input, CheckBox, Button, LinkButton, NavButtonGroup } from '@servicestack/react'; 4 | import { withRouter } from 'react-router-dom'; 5 | import { StateContext, client, Routes, queryString, redirect, classNames } from '../shared'; 6 | import { Authenticate } from '../shared/dtos'; 7 | 8 | export const SignIn = withRouter(({ history }) => { 9 | const {state, dispatch} = useContext(StateContext); 10 | 11 | const redirectTo = queryString(history.location.search).redirect || Routes.Home; 12 | if (state.userSession != null) { 13 | redirect(history, redirectTo); 14 | return null; 15 | } 16 | 17 | const [loading, setLoading] = useState(false); 18 | const [responseStatus, setResponseStatus] = useState(null); 19 | 20 | const [userName, setUserName] = useState(''); 21 | const [password, setPassword] = useState(''); 22 | const [rememberMe, setRememberMe] = useState(true); 23 | 24 | const switchUser = (email:string) => { 25 | setUserName(email); 26 | setPassword('p@55wOrd'); 27 | }; 28 | 29 | const submit = async () => { 30 | try { 31 | setLoading(true); 32 | setResponseStatus(null); 33 | 34 | const response = await client.post(new Authenticate({ 35 | provider: 'credentials', 36 | userName, 37 | password, 38 | rememberMe, 39 | })); 40 | 41 | setLoading(false); 42 | dispatch({ type:'signin', data:response }); 43 | redirect(history, redirectTo); 44 | 45 | } catch (e: any) { 46 | setResponseStatus(e.responseStatus || e); 47 | setLoading(false); 48 | } 49 | } 50 | 51 | const handleSubmit = async (e:React.FormEvent) => { e.preventDefault(); await submit(); }; 52 | const switchAdmin = () => switchUser('admin@email.com'); 53 | const switchNewUser = () => switchUser('new@user.com'); 54 | 55 | return (
56 |
57 |

Sign In

58 | 59 |
60 |
61 | 62 |
63 |
64 | 66 |
67 |
68 | 70 |
71 |
72 | 73 | Remember Me 74 | 75 |
76 |
77 | 78 | Register New User 79 |
80 |
81 | 82 |
83 |
Quick Login:
84 |
85 | admin@email.com 86 | new@user.com 87 |
88 |
89 |
90 |
91 |
92 |
93 | 95 |
96 |
97 |
); 98 | }); 99 | -------------------------------------------------------------------------------- /MyApp/src/components/SignUp.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { useState, useContext } from 'react'; 3 | import { StateContext, client, checkAuth, Routes, toPascalCase, splitOnFirst, classNames } from '../shared'; 4 | import { Register } from '../shared/dtos'; 5 | import { ErrorSummary, Input, CheckBox, Button, LinkButton } from '@servicestack/react'; 6 | import { withRouter } from 'react-router-dom'; 7 | 8 | export const SignUp = withRouter(({ history }) => { 9 | const { dispatch } = useContext(StateContext); 10 | 11 | const [loading, setLoading] = useState(false); 12 | const [responseStatus, setResponseStatus] = useState(null); 13 | 14 | const [displayName, setDisplayName] = useState(''); 15 | const [email, setEmail] = useState(''); 16 | const [password, setPassword] = useState(''); 17 | const [confirmPassword, setConfirmPassword] = useState(''); 18 | const [autoLogin, setAutoLogin] = useState(true); 19 | 20 | const newUser = (s:string) => { 21 | const names = s.split('@'); 22 | setDisplayName(toPascalCase(names[0]) + ' ' + toPascalCase(splitOnFirst(names[1],'.')[0])); 23 | setEmail(s); 24 | setPassword('p@55wOrd'); 25 | setConfirmPassword('p@55wOrd'); 26 | } 27 | 28 | const submit = async () => { 29 | try { 30 | setLoading(true); 31 | setResponseStatus(null); 32 | 33 | await client.post(new Register({ 34 | displayName, 35 | email, 36 | password, 37 | confirmPassword, 38 | autoLogin, 39 | })); 40 | 41 | await checkAuth(dispatch); 42 | setLoading(false); 43 | 44 | history.push(Routes.Home); 45 | } catch (e: any) { 46 | setResponseStatus(e.responseStatus || e); 47 | setLoading(false); 48 | } 49 | }; 50 | 51 | const handleSubmit = async (e:React.FormEvent) => { e.preventDefault(); await submit(); }; 52 | const handleNewUser = () => newUser('new@user.com'); 53 | 54 | return (
55 |
56 |

Register New User

57 | 58 |
59 |
60 | 61 |
62 |
63 | 65 |
66 |
67 | 69 |
70 |
71 | 73 |
74 |
75 | 77 |
78 |
79 | 80 | Auto Login 81 | 82 |
83 |
84 | 85 | Sign In 86 |
87 |
88 |
Quick Populate:
89 |

90 | new@user.com 91 |

92 |
93 |
94 |
95 |
); 96 | }); -------------------------------------------------------------------------------- /MyApp/src/index.tsx: -------------------------------------------------------------------------------- 1 | import 'bootstrap/dist/css/bootstrap.css'; 2 | import './app.css'; 3 | 4 | import * as ReactDOM from 'react-dom'; 5 | import { StateProvider } from './shared'; 6 | 7 | import { App } from './App'; 8 | 9 | ReactDOM.render( 10 | , 11 | document.getElementById('root') as HTMLElement 12 | ); 13 | -------------------------------------------------------------------------------- /MyApp/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MyApp/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /MyApp/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | import "@testing-library/jest-dom/extend-expect"; 2 | 3 | global.fetch = require('node-fetch'); 4 | console.error = function(){}; //TODO: remove when fixed https://github.com/facebook/react/issues/14769 5 | -------------------------------------------------------------------------------- /MyApp/src/shared/dtos.ts: -------------------------------------------------------------------------------- 1 | /* Options: 2 | Date: 2020-06-13 20:59:35 3 | Version: 5.91 4 | Tip: To override a DTO option, remove "//" prefix before updating 5 | BaseUrl: https://localhost:5001 6 | 7 | //GlobalNamespace: 8 | //MakePropertiesOptional: False 9 | //AddServiceStackTypes: True 10 | //AddResponseStatus: False 11 | //AddImplicitVersion: 12 | //AddDescriptionAsComments: True 13 | //IncludeTypes: 14 | //ExcludeTypes: 15 | //DefaultImports: 16 | */ 17 | 18 | 19 | export interface IReturn 20 | { 21 | createResponse(): T; 22 | } 23 | 24 | export interface IReturnVoid 25 | { 26 | createResponse(): void; 27 | } 28 | 29 | export interface IHasSessionId 30 | { 31 | sessionId: string; 32 | } 33 | 34 | export interface IHasBearerToken 35 | { 36 | bearerToken: string; 37 | } 38 | 39 | export interface IPost 40 | { 41 | } 42 | 43 | // @DataContract 44 | export class ResponseError 45 | { 46 | // @DataMember(Order=1) 47 | public errorCode: string; 48 | 49 | // @DataMember(Order=2) 50 | public fieldName: string; 51 | 52 | // @DataMember(Order=3) 53 | public message: string; 54 | 55 | // @DataMember(Order=4) 56 | public meta: { [index: string]: string; }; 57 | 58 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 59 | } 60 | 61 | // @DataContract 62 | export class ResponseStatus 63 | { 64 | // @DataMember(Order=1) 65 | public errorCode: string; 66 | 67 | // @DataMember(Order=2) 68 | public message: string; 69 | 70 | // @DataMember(Order=3) 71 | public stackTrace: string; 72 | 73 | // @DataMember(Order=4) 74 | public errors: ResponseError[]; 75 | 76 | // @DataMember(Order=5) 77 | public meta: { [index: string]: string; }; 78 | 79 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 80 | } 81 | 82 | export class HelloResponse 83 | { 84 | public result: string; 85 | 86 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 87 | } 88 | 89 | // @DataContract 90 | export class AuthenticateResponse implements IHasSessionId, IHasBearerToken 91 | { 92 | // @DataMember(Order=11) 93 | public responseStatus: ResponseStatus; 94 | 95 | // @DataMember(Order=1) 96 | public userId: string; 97 | 98 | // @DataMember(Order=2) 99 | public sessionId: string; 100 | 101 | // @DataMember(Order=3) 102 | public userName: string; 103 | 104 | // @DataMember(Order=4) 105 | public displayName: string; 106 | 107 | // @DataMember(Order=5) 108 | public referrerUrl: string; 109 | 110 | // @DataMember(Order=6) 111 | public bearerToken: string; 112 | 113 | // @DataMember(Order=7) 114 | public refreshToken: string; 115 | 116 | // @DataMember(Order=8) 117 | public profileUrl: string; 118 | 119 | // @DataMember(Order=9) 120 | public roles: string[]; 121 | 122 | // @DataMember(Order=10) 123 | public permissions: string[]; 124 | 125 | // @DataMember(Order=12) 126 | public meta: { [index: string]: string; }; 127 | 128 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 129 | } 130 | 131 | // @DataContract 132 | export class AssignRolesResponse 133 | { 134 | // @DataMember(Order=1) 135 | public allRoles: string[]; 136 | 137 | // @DataMember(Order=2) 138 | public allPermissions: string[]; 139 | 140 | // @DataMember(Order=3) 141 | public meta: { [index: string]: string; }; 142 | 143 | // @DataMember(Order=4) 144 | public responseStatus: ResponseStatus; 145 | 146 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 147 | } 148 | 149 | // @DataContract 150 | export class UnAssignRolesResponse 151 | { 152 | // @DataMember(Order=1) 153 | public allRoles: string[]; 154 | 155 | // @DataMember(Order=2) 156 | public allPermissions: string[]; 157 | 158 | // @DataMember(Order=3) 159 | public meta: { [index: string]: string; }; 160 | 161 | // @DataMember(Order=4) 162 | public responseStatus: ResponseStatus; 163 | 164 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 165 | } 166 | 167 | // @DataContract 168 | export class RegisterResponse 169 | { 170 | // @DataMember(Order=1) 171 | public userId: string; 172 | 173 | // @DataMember(Order=2) 174 | public sessionId: string; 175 | 176 | // @DataMember(Order=3) 177 | public userName: string; 178 | 179 | // @DataMember(Order=4) 180 | public referrerUrl: string; 181 | 182 | // @DataMember(Order=5) 183 | public bearerToken: string; 184 | 185 | // @DataMember(Order=6) 186 | public refreshToken: string; 187 | 188 | // @DataMember(Order=7) 189 | public responseStatus: ResponseStatus; 190 | 191 | // @DataMember(Order=8) 192 | public meta: { [index: string]: string; }; 193 | 194 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 195 | } 196 | 197 | // @Route("/hello") 198 | // @Route("/hello/{Name}") 199 | export class Hello implements IReturn 200 | { 201 | public name: string; 202 | 203 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 204 | public createResponse() { return new HelloResponse(); } 205 | public getTypeName() { return 'Hello'; } 206 | } 207 | 208 | // @Route("/auth") 209 | // @Route("/auth/{provider}") 210 | // @DataContract 211 | export class Authenticate implements IReturn, IPost 212 | { 213 | // @DataMember(Order=1) 214 | public provider: string; 215 | 216 | // @DataMember(Order=2) 217 | public state: string; 218 | 219 | // @DataMember(Order=3) 220 | public oauth_token: string; 221 | 222 | // @DataMember(Order=4) 223 | public oauth_verifier: string; 224 | 225 | // @DataMember(Order=5) 226 | public userName: string; 227 | 228 | // @DataMember(Order=6) 229 | public password: string; 230 | 231 | // @DataMember(Order=7) 232 | public rememberMe?: boolean; 233 | 234 | // @DataMember(Order=9) 235 | public errorView: string; 236 | 237 | // @DataMember(Order=10) 238 | public nonce: string; 239 | 240 | // @DataMember(Order=11) 241 | public uri: string; 242 | 243 | // @DataMember(Order=12) 244 | public response: string; 245 | 246 | // @DataMember(Order=13) 247 | public qop: string; 248 | 249 | // @DataMember(Order=14) 250 | public nc: string; 251 | 252 | // @DataMember(Order=15) 253 | public cnonce: string; 254 | 255 | // @DataMember(Order=16) 256 | public useTokenCookie?: boolean; 257 | 258 | // @DataMember(Order=17) 259 | public accessToken: string; 260 | 261 | // @DataMember(Order=18) 262 | public accessTokenSecret: string; 263 | 264 | // @DataMember(Order=19) 265 | public scope: string; 266 | 267 | // @DataMember(Order=20) 268 | public meta: { [index: string]: string; }; 269 | 270 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 271 | public createResponse() { return new AuthenticateResponse(); } 272 | public getTypeName() { return 'Authenticate'; } 273 | } 274 | 275 | // @Route("/assignroles") 276 | // @DataContract 277 | export class AssignRoles implements IReturn, IPost 278 | { 279 | // @DataMember(Order=1) 280 | public userName: string; 281 | 282 | // @DataMember(Order=2) 283 | public permissions: string[]; 284 | 285 | // @DataMember(Order=3) 286 | public roles: string[]; 287 | 288 | // @DataMember(Order=4) 289 | public meta: { [index: string]: string; }; 290 | 291 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 292 | public createResponse() { return new AssignRolesResponse(); } 293 | public getTypeName() { return 'AssignRoles'; } 294 | } 295 | 296 | // @Route("/unassignroles") 297 | // @DataContract 298 | export class UnAssignRoles implements IReturn, IPost 299 | { 300 | // @DataMember(Order=1) 301 | public userName: string; 302 | 303 | // @DataMember(Order=2) 304 | public permissions: string[]; 305 | 306 | // @DataMember(Order=3) 307 | public roles: string[]; 308 | 309 | // @DataMember(Order=4) 310 | public meta: { [index: string]: string; }; 311 | 312 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 313 | public createResponse() { return new UnAssignRolesResponse(); } 314 | public getTypeName() { return 'UnAssignRoles'; } 315 | } 316 | 317 | // @Route("/register") 318 | // @DataContract 319 | export class Register implements IReturn, IPost 320 | { 321 | // @DataMember(Order=1) 322 | public userName: string; 323 | 324 | // @DataMember(Order=2) 325 | public firstName: string; 326 | 327 | // @DataMember(Order=3) 328 | public lastName: string; 329 | 330 | // @DataMember(Order=4) 331 | public displayName: string; 332 | 333 | // @DataMember(Order=5) 334 | public email: string; 335 | 336 | // @DataMember(Order=6) 337 | public password: string; 338 | 339 | // @DataMember(Order=7) 340 | public confirmPassword: string; 341 | 342 | // @DataMember(Order=8) 343 | public autoLogin?: boolean; 344 | 345 | // @DataMember(Order=10) 346 | public errorView: string; 347 | 348 | // @DataMember(Order=11) 349 | public meta: { [index: string]: string; }; 350 | 351 | public constructor(init?: Partial) { (Object as any).assign(this, init); } 352 | public createResponse() { return new RegisterResponse(); } 353 | public getTypeName() { return 'Register'; } 354 | } 355 | 356 | -------------------------------------------------------------------------------- /MyApp/src/shared/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { createContext, useReducer } from 'react'; 3 | import { JsonServiceClient, GetNavItemsResponse, UserAttributes, IAuthSession } from '@servicestack/client'; 4 | import { History } from 'history'; 5 | import { 6 | Authenticate, AuthenticateResponse 7 | } from './dtos'; 8 | 9 | declare let global: any; // populated from package.json/jest 10 | 11 | if (typeof global === 'undefined') { 12 | (window as any).global = window; 13 | } 14 | 15 | export let client = new JsonServiceClient('/'); 16 | 17 | const isNode = typeof process === 'object' && 18 | typeof process.versions === 'object' && 19 | typeof process.versions.node !== 'undefined'; 20 | if (isNode) { 21 | const packageConfig = require("../../package.json"); 22 | let baseUrl = packageConfig["proxy"]; 23 | client = new JsonServiceClient(baseUrl); 24 | if (baseUrl.startsWith("https://localhost") || baseUrl.startsWith("https://127.0.0.1")) { 25 | // allow self-signed certs 26 | client.requestFilter = (req) => { 27 | const https = require('https'); 28 | (req as any).agent = new https.Agent({ rejectUnauthorized: false }); 29 | }; 30 | } 31 | } 32 | 33 | export { 34 | errorResponse, errorResponseExcept, 35 | splitOnFirst, toPascalCase, 36 | queryString, 37 | classNames, 38 | } from '@servicestack/client'; 39 | 40 | export enum Routes { 41 | Home = '/', 42 | About = '/about', 43 | SignIn = '/signin', 44 | SignUp = '/signup', 45 | Profile = '/profile', 46 | Admin = '/admin', 47 | Forbidden = '/forbidden', 48 | } 49 | 50 | export enum Roles { 51 | Admin = 'Admin', 52 | } 53 | 54 | export const redirect = (history: History, path: string) => { 55 | setTimeout(() => { 56 | const externalUrl = path.indexOf('://') >= 0; 57 | if (!externalUrl) { 58 | history.push(path); 59 | } else { 60 | document.location.href = path; 61 | } 62 | }, 0); 63 | } 64 | 65 | // Shared state between all Components 66 | interface State { 67 | nav: GetNavItemsResponse; 68 | userSession: IAuthSession | null; 69 | userAttributes?: string[]; 70 | roles?: string[]; 71 | permissions?: string[]; 72 | } 73 | interface Action { 74 | type: 'signout' | 'signin' 75 | data?: AuthenticateResponse | any 76 | } 77 | 78 | const initialState: State = { 79 | nav: global.NAV_ITEMS as GetNavItemsResponse, 80 | userSession: global.AUTH as AuthenticateResponse, 81 | userAttributes: UserAttributes.fromSession(global.AUTH), 82 | }; 83 | 84 | const reducer = (state: State, action: Action) => { 85 | switch (action.type) { 86 | case 'signin': 87 | const userSession = action.data as IAuthSession; 88 | return { ...state, userSession, roles: userSession.roles || [], permissions: userSession.permissions || [], 89 | userAttributes: UserAttributes.fromSession(userSession) } as State; 90 | case 'signout': 91 | return { nav:state.nav, userSession:null } as State; 92 | default: 93 | throw new Error(); 94 | } 95 | } 96 | 97 | interface Context { 98 | state: State, 99 | dispatch: React.Dispatch 100 | } 101 | 102 | export const StateContext = createContext({} as Context); 103 | 104 | export const StateProvider = (props: any) => { 105 | const [state, dispatch] = useReducer(reducer, initialState); 106 | return ({props.children}); 107 | } 108 | 109 | type Dispatch = React.Dispatch; 110 | 111 | export const checkAuth = async (dispatch: Dispatch) => { 112 | try { 113 | dispatch({ type: 'signin', data: await client.post(new Authenticate()) }); 114 | } catch (e) { 115 | dispatch({ type: 'signout' }); 116 | } 117 | }; 118 | 119 | export const signout = async (dispatch: Dispatch) => { 120 | dispatch({ type: 'signout' }); 121 | await client.post(new Authenticate({ provider: 'logout' })); 122 | }; 123 | -------------------------------------------------------------------------------- /MyApp/src/sum.spec.ts: -------------------------------------------------------------------------------- 1 | import { sum } from './sum'; 2 | 3 | it ('adds 1 + 2 to equal 3 in TypeScript', () => { 4 | expect(sum(1, 2)).toBe(3); 5 | }); 6 | -------------------------------------------------------------------------------- /MyApp/src/sum.ts: -------------------------------------------------------------------------------- 1 | export function sum(a:number, b:number) { 2 | return a + b; 3 | } 4 | -------------------------------------------------------------------------------- /MyApp/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "outDir": "build/dist", 5 | "module": "esnext", 6 | "target": "es5", 7 | "lib": [ 8 | "dom", 9 | "dom.iterable", 10 | "esnext" 11 | ], 12 | "sourceMap": true, 13 | "allowJs": true, 14 | "jsx": "react-jsx", 15 | "moduleResolution": "node", 16 | "rootDir": "src", 17 | "forceConsistentCasingInFileNames": true, 18 | "noImplicitReturns": true, 19 | "noImplicitThis": true, 20 | "noImplicitAny": true, 21 | "strictNullChecks": true, 22 | "suppressImplicitAnyIndexErrors": true, 23 | "noUnusedLocals": false, 24 | "experimentalDecorators": true, 25 | "skipLibCheck": true, 26 | "esModuleInterop": true, 27 | "allowSyntheticDefaultImports": true, 28 | "strict": true, 29 | "noFallthroughCasesInSwitch": true, 30 | "resolveJsonModule": true, 31 | "isolatedModules": true, 32 | "noEmit": true, 33 | "strictPropertyInitialization": false 34 | }, 35 | "exclude": [ 36 | "node_modules", 37 | "bin", 38 | "wwwroot", 39 | "build", 40 | "scripts", 41 | "acceptance-tests", 42 | "webpack", 43 | "jest", 44 | "coverage", 45 | "gulpfile.js", 46 | "src/setupTests.ts" 47 | ], 48 | "include": [ 49 | "src" 50 | ] 51 | } -------------------------------------------------------------------------------- /MyApp/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"], 3 | "linterOptions": { 4 | "exclude": [ 5 | "bin/**", 6 | "wwwroot/**", 7 | "config/**/*.js", 8 | "node_modules/**" 9 | ] 10 | }, 11 | "rules": { 12 | "quotemark": [true, "single", "jsx-double"], 13 | "indent": [true, "spaces", 2], 14 | "interface-name": false, 15 | "ordered-imports": false, 16 | "object-literal-sort-keys": false, 17 | "no-consecutive-blank-lines": false, 18 | "no-trailing-whitespace": [true, "ignore-comments"], 19 | "one-line": false, 20 | "max-classes-per-file": false, 21 | "jsx-boolean-value": false, 22 | "no-empty-interface": false, 23 | "variable-name": [true, "allow-pascal-case", "allow-snake-case"], 24 | "no-console": false, 25 | "interface-over-type-literal": false 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /MyApp/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | React App
-------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-spa 2 | 3 | .NET 6.0 React Webpack App Template 4 | 5 | [![](https://raw.githubusercontent.com/ServiceStack/Assets/master/csharp-templates/react-spa.png)](http://react-spa.web-templates.io/) 6 | 7 | > Browse [source code](https://github.com/NetCoreTemplates/react-spa), view live demo [react-spa.web-templates.io](http://react-spa.web-templates.io) and install with [dotnet-new](https://docs.servicestack.net/dotnet-new): 8 | 9 | $ dotnet tool install -g x 10 | 11 | $ x new LegacyTemplates/react-spa ProjectName 12 | 13 | Alternatively write new project files directly into an empty repository, using the Directory Name as the ProjectName: 14 | 15 | $ git clone https://github.com//.git 16 | $ cd 17 | $ x new react-spa 18 | 19 | ## Development workflow 20 | 21 | Our recommendation during development is to run the `dev` npm script or Gulp task and leave it running in the background: 22 | 23 | $ npm run dev 24 | 25 | This initially generates a full development build of your Web App then stays running in the background to process files as they’re changed. This enables the normal dev workflow of running your ASP.NET Web App, saving changes locally which are then reloaded using ServiceStack’s built-in hot reloading. Alternatively hitting `F5` will refresh the page and view the latest changes. 26 | 27 | Each change updates the output dev resources so even if you stop the dev task your Web App remains in a working state that’s viewable when running the ASP.NET Web App. 28 | 29 | ### Watched .NET Core builds 30 | 31 | .NET Core projects can also benefit from Live Coding using dotnet watch which performs a “watched build” where it automatically stops, recompiles and restarts your .NET Core App when it detects source file changes. You can start a watched build from the command-line with: 32 | 33 | $ dotnet watch run 34 | 35 | ### Create a production build 36 | 37 | Run the `build` npm script or gulp task to generate a static production build of your App saved to your .NET App's `/wwwroot` folder: 38 | 39 | $ npm run build 40 | 41 | This will let you run the production build of your App that's hosted by your .NET App. 42 | 43 | ### Updating Server TypeScript DTOs 44 | 45 | Run the `dtos` npm script or Gulp task to update your server dtos in `/src/dtos.ts`: 46 | 47 | $ npm run dtos 48 | 49 | ### Deployments 50 | 51 | When your App is ready to deploy, run the `publish` npm (or Gulp) script to package your App for deployment: 52 | 53 | $ npm run publish 54 | 55 | Which will create a production build of your App which then runs `dotnet publish -c Release` to Publish a Release build of your App in the `/bin/net5/publish` folder which can then copied to remote server or an included in a Docker container to deploy your App. 56 | 57 | ### Testing 58 | 59 | Run the `test` npm script or gulp task to launch the test runner in the interactive watch mode: 60 | 61 | $ npm test 62 | 63 | To view test coverage of your tests run the `tests-coverage` npm script or gulp task: 64 | 65 | $ npm run tests-coverage 66 | 67 | ## Create React App 68 | 69 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 70 | 71 | Below you will find some information on how to perform common tasks.
72 | 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). 73 | 74 | ## Table of Contents 75 | 76 | - [Updating to New Releases](#updating-to-new-releases) 77 | - [Sending Feedback](#sending-feedback) 78 | - [Folder Structure](#folder-structure) 79 | - [Available Scripts](#available-scripts) 80 | - [npm start](#npm-start) 81 | - [npm test](#npm-test) 82 | - [npm run build](#npm-run-build) 83 | - [npm run eject](#npm-run-eject) 84 | - [Supported Browsers](#supported-browsers) 85 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 86 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 87 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 88 | - [Debugging in the Editor](#debugging-in-the-editor) 89 | - [Formatting Code Automatically](#formatting-code-automatically) 90 | - [Changing the Page ``](#changing-the-page-title) 91 | - [Installing a Dependency](#installing-a-dependency) 92 | - [Importing a Component](#importing-a-component) 93 | - [Code Splitting](#code-splitting) 94 | - [Adding a Stylesheet](#adding-a-stylesheet) 95 | - [Post-Processing CSS](#post-processing-css) 96 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 97 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) 98 | - [Using the `public` Folder](#using-the-public-folder) 99 | - [Changing the HTML](#changing-the-html) 100 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 101 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 102 | - [Using Global Variables](#using-global-variables) 103 | - [Adding Bootstrap](#adding-bootstrap) 104 | - [Using a Custom Theme](#using-a-custom-theme) 105 | - [Adding Flow](#adding-flow) 106 | - [Adding a Router](#adding-a-router) 107 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 108 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 109 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 110 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 111 | - [Can I Use Decorators?](#can-i-use-decorators) 112 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) 113 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 114 | - [Node](#node) 115 | - [Ruby on Rails](#ruby-on-rails) 116 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 117 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 118 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 119 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) 120 | - [Using HTTPS in Development](#using-https-in-development) 121 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 122 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 123 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 124 | - [Running Tests](#running-tests) 125 | - [Filename Conventions](#filename-conventions) 126 | - [Command Line Interface](#command-line-interface) 127 | - [Version Control Integration](#version-control-integration) 128 | - [Writing Tests](#writing-tests) 129 | - [Testing Components](#testing-components) 130 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 131 | - [Initializing Test Environment](#initializing-test-environment) 132 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 133 | - [Coverage Reporting](#coverage-reporting) 134 | - [Continuous Integration](#continuous-integration) 135 | - [Disabling jsdom](#disabling-jsdom) 136 | - [Snapshot Testing](#snapshot-testing) 137 | - [Editor Integration](#editor-integration) 138 | - [Debugging Tests](#debugging-tests) 139 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome) 140 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) 141 | - [Developing Components in Isolation](#developing-components-in-isolation) 142 | - [Getting Started with Storybook](#getting-started-with-storybook) 143 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 144 | - [Publishing Components to npm](#publishing-components-to-npm) 145 | - [Making a Progressive Web App](#making-a-progressive-web-app) 146 | - [Opting Out of Caching](#opting-out-of-caching) 147 | - [Offline-First Considerations](#offline-first-considerations) 148 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 149 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 150 | - [Deployment](#deployment) 151 | - [Static Server](#static-server) 152 | - [Other Solutions](#other-solutions) 153 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 154 | - [Building for Relative Paths](#building-for-relative-paths) 155 | - [Azure](#azure) 156 | - [Firebase](#firebase) 157 | - [GitHub Pages](#github-pages) 158 | - [Heroku](#heroku) 159 | - [Netlify](#netlify) 160 | - [Now](#now) 161 | - [S3 and CloudFront](#s3-and-cloudfront) 162 | - [Surge](#surge) 163 | - [Advanced Configuration](#advanced-configuration) 164 | - [Troubleshooting](#troubleshooting) 165 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 166 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 167 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 168 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 169 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 170 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 171 | - [Alternatives to Ejecting](#alternatives-to-ejecting) 172 | - [Something Missing?](#something-missing) 173 | 174 | ## Updating to New Releases 175 | 176 | Create React App is divided into two packages: 177 | 178 | * `create-react-app` is a global command-line utility that you use to create new projects. 179 | * `react-scripts` is a development dependency in the generated projects (including this one). 180 | 181 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 182 | 183 | 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. 184 | 185 | 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. 186 | 187 | 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. 188 | 189 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 190 | 191 | ## Sending Feedback 192 | 193 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 194 | 195 | ## Folder Structure 196 | 197 | After creation, your project should look like this: 198 | 199 | ``` 200 | my-app/ 201 | README.md 202 | node_modules/ 203 | package.json 204 | public/ 205 | index.html 206 | favicon.ico 207 | src/ 208 | App.css 209 | App.js 210 | App.test.js 211 | index.css 212 | index.js 213 | logo.svg 214 | ``` 215 | 216 | For the project to build, **these files must exist with exact filenames**: 217 | 218 | * `public/index.html` is the page template; 219 | * `src/index.js` is the JavaScript entry point. 220 | 221 | You can delete or rename the other files. 222 | 223 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 224 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 225 | 226 | Only files inside `public` can be used from `public/index.html`.<br> 227 | Read instructions below for using assets from JavaScript and HTML. 228 | 229 | You can, however, create more top-level directories.<br> 230 | They will not be included in the production build so you can use them for things like documentation. 231 | 232 | ## Available Scripts 233 | 234 | In the project directory, you can run: 235 | 236 | ### `npm start` 237 | 238 | Runs the app in the development mode.<br> 239 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 240 | 241 | The page will reload if you make edits.<br> 242 | You will also see any lint errors in the console. 243 | 244 | ### `npm test` 245 | 246 | Launches the test runner in the interactive watch mode.<br> 247 | See the section about [running tests](#running-tests) for more information. 248 | 249 | ### `npm run build` 250 | 251 | Builds the app for production to the `build` folder.<br> 252 | It correctly bundles React in production mode and optimizes the build for the best performance. 253 | 254 | The build is minified and the filenames include the hashes.<br> 255 | Your app is ready to be deployed! 256 | 257 | See the section about [deployment](#deployment) for more information. 258 | 259 | ### `npm run eject` 260 | 261 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 262 | 263 | 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. 264 | 265 | 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. 266 | 267 | 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. 268 | 269 | ## Supported Browsers 270 | 271 | By default, the generated project uses the latest version of React. 272 | 273 | You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers. 274 | 275 | ## Supported Language Features and Polyfills 276 | 277 | This project supports a superset of the latest JavaScript standard.<br> 278 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 279 | 280 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 281 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 282 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 283 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 284 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 285 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 286 | 287 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 288 | 289 | 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. 290 | 291 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 292 | 293 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 294 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 295 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 296 | 297 | 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. 298 | 299 | Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to. 300 | 301 | ## Syntax Highlighting in the Editor 302 | 303 | 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. 304 | 305 | ## Displaying Lint Output in the Editor 306 | 307 | >Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 308 | >It also only works with npm 3 or higher. 309 | 310 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 311 | 312 | 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. 313 | 314 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 315 | 316 | ```js 317 | { 318 | "extends": "react-app" 319 | } 320 | ``` 321 | 322 | Now your editor should report the linting warnings. 323 | 324 | 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. 325 | 326 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 327 | 328 | ## Debugging in the Editor 329 | 330 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** 331 | 332 | 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. 333 | 334 | ### Visual Studio Code 335 | 336 | 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. 337 | 338 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 339 | 340 | ```json 341 | { 342 | "version": "0.2.0", 343 | "configurations": [{ 344 | "name": "Chrome", 345 | "type": "chrome", 346 | "request": "launch", 347 | "url": "http://localhost:3000", 348 | "webRoot": "${workspaceRoot}/src", 349 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 350 | "sourceMapPathOverrides": { 351 | "webpack:///src/*": "${webRoot}/*" 352 | } 353 | }] 354 | } 355 | ``` 356 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 357 | 358 | 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. 359 | 360 | ### WebStorm 361 | 362 | 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. 363 | 364 | 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. 365 | 366 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 367 | 368 | 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. 369 | 370 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. 371 | 372 | ## Formatting Code Automatically 373 | 374 | 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/). 375 | 376 | To format our code whenever we make a commit in git, we need to install the following dependencies: 377 | 378 | ```sh 379 | npm install --save husky lint-staged prettier 380 | ``` 381 | 382 | Alternatively you may use `yarn`: 383 | 384 | ```sh 385 | yarn add husky lint-staged prettier 386 | ``` 387 | 388 | * `husky` makes it easy to use githooks as if they are npm scripts. 389 | * `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). 390 | * `prettier` is the JavaScript formatter we will run before commits. 391 | 392 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 393 | 394 | Add the following line to `scripts` section: 395 | 396 | ```diff 397 | "scripts": { 398 | + "precommit": "lint-staged", 399 | "start": "react-scripts start", 400 | "build": "react-scripts build", 401 | ``` 402 | 403 | Next we add a 'lint-staged' field to the `package.json`, for example: 404 | 405 | ```diff 406 | "dependencies": { 407 | // ... 408 | }, 409 | + "lint-staged": { 410 | + "src/**/*.{js,jsx,json,css}": [ 411 | + "prettier --single-quote --write", 412 | + "git add" 413 | + ] 414 | + }, 415 | "scripts": { 416 | ``` 417 | 418 | 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,json,css}"` to format your entire project for the first time. 419 | 420 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page. 421 | 422 | ## Changing the Page `<title>` 423 | 424 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 425 | 426 | 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. 427 | 428 | 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. 429 | 430 | 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). 431 | 432 | ## Installing a Dependency 433 | 434 | 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`: 435 | 436 | ```sh 437 | npm install --save react-router 438 | ``` 439 | 440 | Alternatively you may use `yarn`: 441 | 442 | ```sh 443 | yarn add react-router 444 | ``` 445 | 446 | This works for any library, not just `react-router`. 447 | 448 | ## Importing a Component 449 | 450 | This project setup supports ES6 modules thanks to Babel.<br> 451 | 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. 452 | 453 | For example: 454 | 455 | ### `Button.js` 456 | 457 | ```js 458 | import React, { Component } from 'react'; 459 | 460 | class Button extends Component { 461 | render() { 462 | // ... 463 | } 464 | } 465 | 466 | export default Button; // Don’t forget to use export default! 467 | ``` 468 | 469 | ### `DangerButton.js` 470 | 471 | 472 | ```js 473 | import React, { Component } from 'react'; 474 | import Button from './Button'; // Import a component from another file 475 | 476 | class DangerButton extends Component { 477 | render() { 478 | return <Button color="red" />; 479 | } 480 | } 481 | 482 | export default DangerButton; 483 | ``` 484 | 485 | 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. 486 | 487 | 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'`. 488 | 489 | 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. 490 | 491 | Learn more about ES6 modules: 492 | 493 | * [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) 494 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 495 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 496 | 497 | ## Code Splitting 498 | 499 | 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. 500 | 501 | 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. 502 | 503 | Here is an example: 504 | 505 | ### `moduleA.js` 506 | 507 | ```js 508 | const moduleA = 'Hello'; 509 | 510 | export { moduleA }; 511 | ``` 512 | ### `App.js` 513 | 514 | ```js 515 | import React, { Component } from 'react'; 516 | 517 | class App extends Component { 518 | handleClick = () => { 519 | import('./moduleA') 520 | .then(({ moduleA }) => { 521 | // Use moduleA 522 | }) 523 | .catch(err => { 524 | // Handle failure 525 | }); 526 | }; 527 | 528 | render() { 529 | return ( 530 | <div> 531 | <button onClick={this.handleClick}>Load</button> 532 | </div> 533 | ); 534 | } 535 | } 536 | 537 | export default App; 538 | ``` 539 | 540 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 541 | 542 | You can also use it with `async` / `await` syntax if you prefer it. 543 | 544 | ### With React Router 545 | 546 | 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). 547 | 548 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. 549 | 550 | ## Adding a Stylesheet 551 | 552 | 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**: 553 | 554 | ### `Button.css` 555 | 556 | ```css 557 | .Button { 558 | padding: 20px; 559 | } 560 | ``` 561 | 562 | ### `Button.js` 563 | 564 | ```js 565 | import React, { Component } from 'react'; 566 | import './Button.css'; // Tell Webpack that Button.js uses these styles 567 | 568 | class Button extends Component { 569 | render() { 570 | // You can use them as regular CSS styles 571 | return <div className="Button" />; 572 | } 573 | } 574 | ``` 575 | 576 | **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. 577 | 578 | 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. 579 | 580 | 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. 581 | 582 | ## Post-Processing CSS 583 | 584 | 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. 585 | 586 | For example, this: 587 | 588 | ```css 589 | .App { 590 | display: flex; 591 | flex-direction: row; 592 | align-items: center; 593 | } 594 | ``` 595 | 596 | becomes this: 597 | 598 | ```css 599 | .App { 600 | display: -webkit-box; 601 | display: -ms-flexbox; 602 | display: flex; 603 | -webkit-box-orient: horizontal; 604 | -webkit-box-direction: normal; 605 | -ms-flex-direction: row; 606 | flex-direction: row; 607 | -webkit-box-align: center; 608 | -ms-flex-align: center; 609 | align-items: center; 610 | } 611 | ``` 612 | 613 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 614 | 615 | ## Adding a CSS Preprocessor (Sass, Less etc.) 616 | 617 | 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 `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 618 | 619 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 620 | 621 | First, let’s install the command-line interface for Sass: 622 | 623 | ```sh 624 | npm install --save node-sass-chokidar 625 | ``` 626 | 627 | Alternatively you may use `yarn`: 628 | 629 | ```sh 630 | yarn add node-sass-chokidar 631 | ``` 632 | 633 | Then in `package.json`, add the following lines to `scripts`: 634 | 635 | ```diff 636 | "scripts": { 637 | + "build-css": "node-sass-chokidar src/ -o src/", 638 | + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 639 | "start": "react-scripts start", 640 | "build": "react-scripts build", 641 | "test": "react-scripts test --env=jsdom", 642 | ``` 643 | 644 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 645 | 646 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 647 | 648 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 649 | 650 | To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. 651 | 652 | ``` 653 | "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", 654 | "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", 655 | ``` 656 | 657 | This will allow you to do imports like 658 | 659 | ```scss 660 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 661 | @import 'nprogress/nprogress'; // importing a css file from the nprogress node module 662 | ``` 663 | 664 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 665 | 666 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 667 | 668 | ```sh 669 | npm install --save npm-run-all 670 | ``` 671 | 672 | Alternatively you may use `yarn`: 673 | 674 | ```sh 675 | yarn add npm-run-all 676 | ``` 677 | 678 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 679 | 680 | ```diff 681 | "scripts": { 682 | "build-css": "node-sass-chokidar src/ -o src/", 683 | "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 684 | - "start": "react-scripts-ts start", 685 | - "build": "react-scripts-ts build", 686 | + "start-js": "react-scripts-ts start", 687 | + "start": "npm-run-all -p watch-css start-js", 688 | + "build": "npm run build-css && react-scripts-ts build", 689 | "test": "react-scripts test --env=jsdom", 690 | "eject": "react-scripts eject" 691 | } 692 | ``` 693 | 694 | Now running `npm start` and `npm run build` also builds Sass files. 695 | 696 | **Why `node-sass-chokidar`?** 697 | 698 | `node-sass` has been reported as having the following issues: 699 | 700 | - `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. 701 | 702 | - Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) 703 | 704 | - `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) 705 | 706 | `node-sass-chokidar` is used here as it addresses these issues. 707 | 708 | ## Adding Images, Fonts, and Files 709 | 710 | With Webpack, using static assets like images and fonts works similarly to CSS. 711 | 712 | You can **`import` a file right in a TypeScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. 713 | 714 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153). 715 | 716 | Before getting started, you must define each type of asset as a valid module format. Otherwise, the TypeScript compiler will generate an error like this: 717 | 718 | >Cannot find module './logo.png'. 719 | 720 | To import asset files in TypeScript, create a new type definition file in your project, and name it something like `assets.d.ts`. Then, add a line for each type of asset that you need to import: 721 | 722 | ```ts 723 | declare module "*.gif"; 724 | declare module "*.jpg"; 725 | declare module "*.jpeg"; 726 | declare module "*.png"; 727 | declare module "*.svg"; 728 | ``` 729 | (you'll have to restart the compiler in order the changes to take place) 730 | 731 | In this case, we've added several image file extensions as valid module formats. 732 | 733 | Now that the compiler is configured, here is an example of importing an image file: 734 | 735 | ```js 736 | import React from 'react'; 737 | import logo from './logo.svg'; // Tell Webpack this JS file uses this image 738 | 739 | console.log(logo); // /logo.84287d09.png 740 | 741 | function Header() { 742 | // Import result is the URL of your image 743 | return <img src={logo} alt="Logo" />; 744 | } 745 | 746 | export default Header; 747 | ``` 748 | 749 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 750 | 751 | This works in CSS too: 752 | 753 | ```css 754 | .Logo { 755 | background-image: url(./logo.png); 756 | } 757 | ``` 758 | 759 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 760 | 761 | Please be advised that this is also a custom feature of Webpack. 762 | 763 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 764 | An alternative way of handling static assets is described in the next section. 765 | 766 | ## Using the `public` Folder 767 | 768 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 769 | 770 | ### Changing the HTML 771 | 772 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 773 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 774 | 775 | ### Adding Assets Outside of the Module System 776 | 777 | You can also add other assets to the `public` folder. 778 | 779 | Note that we normally encourage you to `import` assets in JavaScript files instead. 780 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 781 | This mechanism provides a number of benefits: 782 | 783 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 784 | * Missing files cause compilation errors instead of 404 errors for your users. 785 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 786 | 787 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 788 | 789 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 790 | 791 | Inside `index.html`, you can use it like this: 792 | 793 | ```html 794 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 795 | ``` 796 | 797 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 798 | 799 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 800 | 801 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 802 | 803 | ```js 804 | render() { 805 | // Note: this is an escape hatch and should be used sparingly! 806 | // Normally we recommend using `import` for getting asset URLs 807 | // as described in “Adding Images and Fonts” above this section. 808 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 809 | } 810 | ``` 811 | 812 | Keep in mind the downsides of this approach: 813 | 814 | * None of the files in `public` folder get post-processed or minified. 815 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 816 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 817 | 818 | ### When to Use the `public` Folder 819 | 820 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 821 | The `public` folder is useful as a workaround for a number of less common cases: 822 | 823 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 824 | * You have thousands of images and need to dynamically reference their paths. 825 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 826 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 827 | 828 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 829 | 830 | ## Using Global Variables 831 | 832 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 833 | 834 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 835 | 836 | ```js 837 | const $ = window.$; 838 | ``` 839 | 840 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 841 | 842 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 843 | 844 | ## Adding Bootstrap 845 | 846 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 847 | 848 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 849 | 850 | ```sh 851 | npm install --save react-bootstrap bootstrap@3 852 | ``` 853 | 854 | Alternatively you may use `yarn`: 855 | 856 | ```sh 857 | yarn add react-bootstrap bootstrap@3 858 | ``` 859 | 860 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 861 | 862 | ```js 863 | import 'bootstrap/dist/css/bootstrap.css'; 864 | import 'bootstrap/dist/css/bootstrap-theme.css'; 865 | // Put any other imports below so that CSS from your 866 | // components takes precedence over default styles. 867 | ``` 868 | 869 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 870 | 871 | ```js 872 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 873 | ``` 874 | 875 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 876 | 877 | ### Using a Custom Theme 878 | 879 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 880 | We suggest the following approach: 881 | 882 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 883 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 884 | * Install your own theme npm package as a dependency of your app. 885 | 886 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 887 | 888 | ## Adding Flow 889 | 890 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 891 | 892 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 893 | 894 | To add Flow to a Create React App project, follow these steps: 895 | 896 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 897 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 898 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 899 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 900 | 901 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 902 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 903 | In the future we plan to integrate it into Create React App even more closely. 904 | 905 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 906 | 907 | ## Adding a Router 908 | 909 | Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/) is the most popular one. 910 | 911 | To add it, run: 912 | 913 | ```sh 914 | npm install --save react-router-dom 915 | ``` 916 | 917 | Alternatively you may use `yarn`: 918 | 919 | ```sh 920 | yarn add react-router-dom 921 | ``` 922 | 923 | To try it, delete all the code in `src/App.js` and replace it with any of the examples on its website. The [Basic Example](https://reacttraining.com/react-router/web/example/basic) is a good place to get started. 924 | 925 | Note that [you may need to configure your production server to support client-side routing](#serving-apps-with-client-side-routing) before deploying your app. 926 | 927 | ## Adding Custom Environment Variables 928 | 929 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 930 | 931 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 932 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 933 | `REACT_APP_`. 934 | 935 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 936 | 937 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 938 | 939 | These environment variables will be defined for you on `process.env`. For example, having an environment 940 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 941 | 942 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 943 | 944 | These environment variables can be useful for displaying information conditionally based on where the project is 945 | deployed or consuming sensitive data that lives outside of version control. 946 | 947 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 948 | in the environment inside a `<form>`: 949 | 950 | ```jsx 951 | render() { 952 | return ( 953 | <div> 954 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 955 | <form> 956 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 957 | </form> 958 | </div> 959 | ); 960 | } 961 | ``` 962 | 963 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 964 | 965 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 966 | 967 | ```html 968 | <div> 969 | <small>You are running this application in <b>development</b> mode.</small> 970 | <form> 971 | <input type="hidden" value="abcdef" /> 972 | </form> 973 | </div> 974 | ``` 975 | 976 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 977 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 978 | a `.env` file. Both of these ways are described in the next few sections. 979 | 980 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 981 | 982 | ```js 983 | if (process.env.NODE_ENV !== 'production') { 984 | analytics.disable(); 985 | } 986 | ``` 987 | 988 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 989 | 990 | ### Referencing Environment Variables in the HTML 991 | 992 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 993 | 994 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 995 | 996 | ```html 997 | <title>%REACT_APP_WEBSITE_NAME% 998 | ``` 999 | 1000 | Note that the caveats from the above section apply: 1001 | 1002 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 1003 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 1004 | 1005 | ### Adding Temporary Environment Variables In Your Shell 1006 | 1007 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 1008 | life of the shell session. 1009 | 1010 | #### Windows (cmd.exe) 1011 | 1012 | ```cmd 1013 | set "REACT_APP_SECRET_CODE=abcdef" && npm start 1014 | ``` 1015 | 1016 | (Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) 1017 | 1018 | #### Windows (Powershell) 1019 | 1020 | ```Powershell 1021 | ($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) 1022 | ``` 1023 | 1024 | #### Linux, macOS (Bash) 1025 | 1026 | ```bash 1027 | REACT_APP_SECRET_CODE=abcdef npm start 1028 | ``` 1029 | 1030 | ### Adding Development Environment Variables In `.env` 1031 | 1032 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 1033 | 1034 | To define permanent environment variables, create a file called `.env` in the root of your project: 1035 | 1036 | ``` 1037 | REACT_APP_SECRET_CODE=abcdef 1038 | ``` 1039 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 1040 | 1041 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 1042 | 1043 | #### What other `.env` files are can be used? 1044 | 1045 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 1046 | 1047 | * `.env`: Default. 1048 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 1049 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 1050 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 1051 | 1052 | Files on the left have more priority than files on the right: 1053 | 1054 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 1055 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 1056 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 1057 | 1058 | These variables will act as the defaults if the machine does not explicitly set them.
1059 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 1060 | 1061 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 1062 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 1063 | 1064 | #### Expanding Environment Variables In `.env` 1065 | 1066 | >Note: this feature is available with `react-scripts@1.1.0` and higher. 1067 | 1068 | Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). 1069 | 1070 | For example, to get the environment variable `npm_package_version`: 1071 | 1072 | ``` 1073 | REACT_APP_VERSION=$npm_package_version 1074 | # also works: 1075 | # REACT_APP_VERSION=${npm_package_version} 1076 | ``` 1077 | 1078 | Or expand variables local to the current `.env` file: 1079 | 1080 | ``` 1081 | DOMAIN=www.example.com 1082 | REACT_APP_FOO=$DOMAIN/foo 1083 | REACT_APP_BAR=$DOMAIN/bar 1084 | ``` 1085 | 1086 | ## Can I Use Decorators? 1087 | 1088 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
1089 | Create React App doesn’t support decorator syntax at the moment because: 1090 | 1091 | * It is an experimental proposal and is subject to change. 1092 | * The current specification version is not officially supported by Babel. 1093 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 1094 | 1095 | However in many cases you can rewrite decorator-based code without decorators just as fine.
1096 | Please refer to these two threads for reference: 1097 | 1098 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 1099 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 1100 | 1101 | Create React App will add decorator support when the specification advances to a stable stage. 1102 | 1103 | ## Fetching Data with AJAX Requests 1104 | 1105 | React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like [axios](https://github.com/axios/axios) or the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by the browser. Conveniently, Create React App includes a polyfill for `fetch()` so you can use it without worrying about the browser support. 1106 | 1107 | The global `fetch` function allows to easily makes AJAX requests. It takes in a URL as an input and returns a `Promise` that resolves to a `Response` object. You can find more information about `fetch` [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). 1108 | 1109 | This project also includes a [Promise polyfill](https://github.com/then/promise) which provides a full implementation of Promises/A+. A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises [here](https://www.promisejs.org/) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Both axios and `fetch()` use Promises under the hood. You can also use the [`async / await`](https://davidwalsh.name/async-await) syntax to reduce the callback nesting. 1110 | 1111 | You can learn more about making AJAX requests from React components in [the FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). 1112 | 1113 | ## Integrating with an API Backend 1114 | 1115 | These tutorials will help you to integrate your app with an API backend running on another port, 1116 | using `fetch()` to access it. 1117 | 1118 | ### Node 1119 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 1120 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 1121 | 1122 | ### Ruby on Rails 1123 | 1124 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 1125 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 1126 | 1127 | ## Proxying API Requests in Development 1128 | 1129 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 1130 | 1131 | People often serve the front-end React app from the same host and port as their backend implementation.
1132 | For example, a production setup might look like this after the app is deployed: 1133 | 1134 | ``` 1135 | / - static server returns index.html with React app 1136 | /todos - static server returns index.html with React app 1137 | /api/todos - server handles any /api/* requests using the backend implementation 1138 | ``` 1139 | 1140 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 1141 | 1142 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 1143 | 1144 | ```js 1145 | "proxy": "http://localhost:4000", 1146 | ``` 1147 | 1148 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 1149 | 1150 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 1151 | 1152 | ``` 1153 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 1154 | ``` 1155 | 1156 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 1157 | 1158 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
1159 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 1160 | 1161 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 1162 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 1163 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 1164 | 1165 | ### "Invalid Host Header" Errors After Configuring Proxy 1166 | 1167 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 1168 | 1169 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 1170 | 1171 | >Invalid Host header 1172 | 1173 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 1174 | 1175 | ``` 1176 | HOST=mypublicdevhost.com 1177 | ``` 1178 | 1179 | If you restart the development server now and load the app from the specified host, it should work. 1180 | 1181 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 1182 | 1183 | ``` 1184 | # NOTE: THIS IS DANGEROUS! 1185 | # It exposes your machine to attacks from the websites you visit. 1186 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1187 | ``` 1188 | 1189 | We don’t recommend this approach. 1190 | 1191 | ### Configuring the Proxy Manually 1192 | 1193 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 1194 | 1195 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
1196 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 1197 | ```js 1198 | { 1199 | // ... 1200 | "proxy": { 1201 | "/api": { 1202 | "target": "", 1203 | "ws": true 1204 | // ... 1205 | } 1206 | } 1207 | // ... 1208 | } 1209 | ``` 1210 | 1211 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 1212 | 1213 | If you need to specify multiple proxies, you may do so by specifying additional entries. 1214 | You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. 1215 | ```js 1216 | { 1217 | // ... 1218 | "proxy": { 1219 | // Matches any request starting with /api 1220 | "/api": { 1221 | "target": "", 1222 | "ws": true 1223 | // ... 1224 | }, 1225 | // Matches any request starting with /foo 1226 | "/foo": { 1227 | "target": "", 1228 | "ssl": true, 1229 | "pathRewrite": { 1230 | "^/foo": "/foo/beta" 1231 | } 1232 | // ... 1233 | }, 1234 | // Matches /bar/abc.html but not /bar/sub/def.html 1235 | "/bar/*.html": { 1236 | "target": "", 1237 | // ... 1238 | }, 1239 | // Matches /baz/abc.html and /baz/sub/def.html 1240 | "/baz/**/*.html": { 1241 | "target": "" 1242 | // ... 1243 | } 1244 | } 1245 | // ... 1246 | } 1247 | ``` 1248 | 1249 | ### Configuring a WebSocket Proxy 1250 | 1251 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 1252 | 1253 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 1254 | 1255 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 1256 | 1257 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 1258 | 1259 | Either way, you can proxy WebSocket requests manually in `package.json`: 1260 | 1261 | ```js 1262 | { 1263 | // ... 1264 | "proxy": { 1265 | "/socket": { 1266 | // Your compatible WebSocket server 1267 | "target": "ws://", 1268 | // Tell http-proxy-middleware that this is a WebSocket proxy. 1269 | // Also allows you to proxy WebSocket requests without an additional HTTP request 1270 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 1271 | "ws": true 1272 | // ... 1273 | } 1274 | } 1275 | // ... 1276 | } 1277 | ``` 1278 | 1279 | ## Using HTTPS in Development 1280 | 1281 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 1282 | 1283 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 1284 | 1285 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1286 | 1287 | #### Windows (cmd.exe) 1288 | 1289 | ```cmd 1290 | set HTTPS=true&&npm start 1291 | ``` 1292 | 1293 | #### Windows (Powershell) 1294 | 1295 | ```Powershell 1296 | ($env:HTTPS = $true) -and (npm start) 1297 | ``` 1298 | 1299 | (Note: the lack of whitespace is intentional.) 1300 | 1301 | #### Linux, macOS (Bash) 1302 | 1303 | ```bash 1304 | HTTPS=true npm start 1305 | ``` 1306 | 1307 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1308 | 1309 | ## Generating Dynamic `` Tags on the Server 1310 | 1311 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1312 | 1313 | ```html 1314 | 1315 | 1316 | 1317 | 1318 | 1319 | ``` 1320 | 1321 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 1322 | 1323 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1324 | 1325 | ## Pre-Rendering into Static HTML Files 1326 | 1327 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1328 | 1329 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1330 | 1331 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1332 | 1333 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1334 | 1335 | ## Injecting Data from the Server into the Page 1336 | 1337 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1338 | 1339 | ```js 1340 | 1341 | 1342 | 1343 | 1346 | ``` 1347 | 1348 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 1349 | 1350 | ## Running Tests 1351 | 1352 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1353 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 1354 | 1355 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 1356 | 1357 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 1358 | 1359 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 1360 | 1361 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 1362 | 1363 | ### Filename Conventions 1364 | 1365 | Jest will look for test files with any of the following popular naming conventions: 1366 | 1367 | * Files with `.js` suffix in `__tests__` folders. 1368 | * Files with `.test.js` suffix. 1369 | * Files with `.spec.js` suffix. 1370 | 1371 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1372 | 1373 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 1374 | 1375 | ### Command Line Interface 1376 | 1377 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 1378 | 1379 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 1380 | 1381 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1382 | 1383 | ### Version Control Integration 1384 | 1385 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 1386 | 1387 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 1388 | 1389 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 1390 | 1391 | ### Writing Tests 1392 | 1393 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 1394 | 1395 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1396 | 1397 | ```js 1398 | import sum from './sum'; 1399 | 1400 | it('sums numbers', () => { 1401 | expect(sum(1, 2)).toEqual(3); 1402 | expect(sum(2, 2)).toEqual(4); 1403 | }); 1404 | ``` 1405 | 1406 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1407 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 1408 | 1409 | ### Testing Components 1410 | 1411 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 1412 | 1413 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 1414 | 1415 | ```ts 1416 | import * as React from 'react'; 1417 | import * as ReactDOM from 'react-dom'; 1418 | import App from './App'; 1419 | 1420 | it('renders without crashing', () => { 1421 | const div = document.createElement('div'); 1422 | ReactDOM.render(, div); 1423 | }); 1424 | ``` 1425 | 1426 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.tsx`. 1427 | 1428 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 1429 | 1430 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: 1431 | 1432 | ```sh 1433 | npm install --save-dev enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer @types/react-test-renderer 1434 | ``` 1435 | 1436 | Alternatively you may use `yarn`: 1437 | 1438 | ```sh 1439 | yarn add --dev enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer @types/react-test-renderer 1440 | ``` 1441 | 1442 | #### `src/setupTests.ts` 1443 | ```ts 1444 | import * as Enzyme from 'enzyme'; 1445 | import * as Adapter from 'enzyme-adapter-react-16'; 1446 | 1447 | Enzyme.configure({ adapter: new Adapter() }); 1448 | ``` 1449 | 1450 | >Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting. 1451 | 1452 | Now you can write a smoke test with it: 1453 | 1454 | ```ts 1455 | import * as React from 'react'; 1456 | import { shallow } from 'enzyme'; 1457 | import App from './App'; 1458 | 1459 | it('renders without crashing', () => { 1460 | shallow(); 1461 | }); 1462 | ``` 1463 | 1464 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `