Step 27: Building an SPA

Building an SPA

Most of the comments will be submitted during the conference where some people do not bring a laptop. But they probably have a smartphone. What about creating a mobile app to quickly check the conference comments?

One way to create such a mobile application is to build a Javascript Single Page Application (SPA). An SPA runs locally, can use local storage, can call a remote HTTP API, and can leverage service workers to create an almost native experience.

Creating the Application

To create the mobile application, we are going to use Preact and Symfony Encore. Preact is a small and efficient foundation well-suited for the Guestbook SPA.

To make both the website and the SPA consistent, we are going to reuse the Sass stylesheets of the website for the mobile application.

Create the SPA application under the spa directory and copy the website stylesheets:

  1. $ mkdir -p spa/src spa/public spa/assets/styles
  2. $ cp assets/styles/*.scss spa/assets/styles/
  3. $ cd spa

Note

We have created a public directory as we will mainly interact with the SPA via a browser. We could have named it build if we only wanted to build a mobile application.

Initialize the package.json file (equivalent of the composer.json file for JavaScript):

  1. $ yarn init -y

Now, add some required dependencies:

  1. $ yarn add @symfony/webpack-encore @babel/core @babel/preset-env babel-preset-preact preact html-webpack-plugin bootstrap

For good measure, add a .gitignore file:

.gitignore

  1. /node_modules
  2. /public
  3. /yarn-error.log
  4. # used later by Cordova
  5. /app

The last configuration step is to create the Webpack Encore configuration:

webpack.config.js

  1. const Encore = require('@symfony/webpack-encore');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. Encore
  4. .setOutputPath('public/')
  5. .setPublicPath('/')
  6. .cleanupOutputBeforeBuild()
  7. .addEntry('app', './src/app.js')
  8. .enablePreactPreset()
  9. .enableSingleRuntimeChunk()
  10. .addPlugin(new HtmlWebpackPlugin({ template: 'src/index.ejs', alwaysWriteToDisk: true }))
  11. ;
  12. module.exports = Encore.getWebpackConfig();

Creating the SPA Main Template

Time to create the initial template in which Preact will render the application:

src/index.ejs

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="msapplication-tap-highlight" content="no" />
  7. <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
  8. <title>Conference Guestbook application</title>
  9. </head>
  10. <body>
  11. <div id="app"></div>
  12. </body>
  13. </html>

The <div> tag is where the application will be rendered by JavaScript. Here is the first version of the code that renders the “Hello World” view:

src/app.js

  1. import {h, render} from 'preact';
  2. function App() {
  3. return (
  4. <div>
  5. Hello world!
  6. </div>
  7. )
  8. }
  9. render(<App />, document.getElementById('app'));

The last line registers the App() function on the #app element of the HTML page.

Everything is now ready!

Running an SPA in the Browser

As this application is independent of the main website, we need to run another web server:

  1. $ symfony server:stop
  1. $ symfony server:start -d --passthru=index.html

The --passthru flag tells the web server to pass all HTTP requests to the public/index.html file (public/ is the web server default web root directory). This page is managed by the Preact application and it gets the page to render via the “browser” history.

To compile the CSS and the JavaScript files, run yarn:

  1. $ yarn encore dev

Open the SPA in a browser:

  1. $ symfony open:local

And look at our hello world SPA:

Step 27: Building an SPA - 图1

Adding a Router to handle States

The SPA is currently not able to handle different pages. To implement several pages, we need a router, like for Symfony. We are going to use preact-router. It takes a URL as an input and matches a Preact component to display.

Install preact-router:

  1. $ yarn add preact-router

Create a page for the homepage (a Preact component):

src/pages/home.js

  1. import {h} from 'preact';
  2. export default function Home() {
  3. return (
  4. <div>Home</div>
  5. );
  6. };

And another for the conference page:

src/pages/conference.js

  1. import {h} from 'preact';
  2. export default function Conference() {
  3. return (
  4. <div>Conference</div>
  5. );
  6. };

Replace the “Hello World” div with the Router component:

patch_file

  1. --- a/src/app.js
  2. +++ b/src/app.js
  3. @@ -1,9 +1,22 @@
  4. import {h, render} from 'preact';
  5. +import {Router, Link} from 'preact-router';
  6. +
  7. +import Home from './pages/home';
  8. +import Conference from './pages/conference';
  9. function App() {
  10. return (
  11. <div>
  12. - Hello world!
  13. + <header>
  14. + <Link href="/">Home</Link>
  15. + <br />
  16. + <Link href="/conference/amsterdam2019">Amsterdam 2019</Link>
  17. + </header>
  18. +
  19. + <Router>
  20. + <Home path="/" />
  21. + <Conference path="/conference/:slug" />
  22. + </Router>
  23. </div>
  24. )
  25. }

Rebuild the application:

  1. $ yarn encore dev

If you refresh the application in the browser, you can now click on the “Home” and conference links. Note that the browser URL and the back/forward buttons of your browser work as you would expect it.

Styling the SPA

As for the website, let’s add the Sass loader:

  1. $ yarn add node-sass sass-loader

Enable the Sass loader in Webpack and add a reference to the stylesheet:

patch_file

  1. --- a/src/app.js
  2. +++ b/src/app.js
  3. @@ -1,3 +1,5 @@
  4. +import '../assets/styles/app.scss';
  5. +
  6. import {h, render} from 'preact';
  7. import {Router, Link} from 'preact-router';
  8. --- a/webpack.config.js
  9. +++ b/webpack.config.js
  10. @@ -7,6 +7,7 @@ Encore
  11. .cleanupOutputBeforeBuild()
  12. .addEntry('app', './src/app.js')
  13. .enablePreactPreset()
  14. + .enableSassLoader()
  15. .enableSingleRuntimeChunk()
  16. .addPlugin(new HtmlWebpackPlugin({ template: 'src/index.ejs', alwaysWriteToDisk: true }))
  17. ;

We can now update the application to use the stylesheets:

patch_file

  1. --- a/src/app.js
  2. +++ b/src/app.js
  3. @@ -9,10 +9,20 @@ import Conference from './pages/conference';
  4. function App() {
  5. return (
  6. <div>
  7. - <header>
  8. - <Link href="/">Home</Link>
  9. - <br />
  10. - <Link href="/conference/amsterdam2019">Amsterdam 2019</Link>
  11. + <header className="header">
  12. + <nav className="navbar navbar-light bg-light">
  13. + <div className="container">
  14. + <Link className="navbar-brand mr-4 pr-2" href="/">
  15. + &#128217; Guestbook
  16. + </Link>
  17. + </div>
  18. + </nav>
  19. +
  20. + <nav className="bg-light border-bottom text-center">
  21. + <Link className="nav-conference" href="/conference/amsterdam2019">
  22. + Amsterdam 2019
  23. + </Link>
  24. + </nav>
  25. </header>
  26. <Router>

Rebuild the application once more:

  1. $ yarn encore dev

You can now enjoy a fully styled SPA:

Step 27: Building an SPA - 图2

Fetching Data from the API

The Preact application structure is now finished: Preact Router handles the page states - including the conference slug placeholder - and the main application stylesheet is used to style the SPA.

To make the SPA dynamic, we need to fetch the data from the API via HTTP calls.

Configure Webpack to expose the API endpoint environment variable:

patch_file

  1. --- a/webpack.config.js
  2. +++ b/webpack.config.js
  3. @@ -1,3 +1,4 @@
  4. +const webpack = require('webpack');
  5. const Encore = require('@symfony/webpack-encore');
  6. const HtmlWebpackPlugin = require('html-webpack-plugin');
  7. @@ -10,6 +11,9 @@ Encore
  8. .enableSassLoader()
  9. .enableSingleRuntimeChunk()
  10. .addPlugin(new HtmlWebpackPlugin({ template: 'src/index.ejs', alwaysWriteToDisk: true }))
  11. + .addPlugin(new webpack.DefinePlugin({
  12. + 'ENV_API_ENDPOINT': JSON.stringify(process.env.API_ENDPOINT),
  13. + }))
  14. ;
  15. module.exports = Encore.getWebpackConfig();

The API_ENDPOINT environment variable should point to the web server of the website where we have the API endpoint under /api. We will configure it properly when we will run yarn encore soon.

Create an api.js file that abstracts data retrieval from the API:

src/api/api.js

  1. function fetchCollection(path) {
  2. return fetch(ENV_API_ENDPOINT + path).then(resp => resp.json()).then(json => json['hydra:member']);
  3. }
  4. export function findConferences() {
  5. return fetchCollection('api/conferences');
  6. }
  7. export function findComments(conference) {
  8. return fetchCollection('api/comments?conference='+conference.id);
  9. }

You can now adapt the header and home components:

patch_file

  1. --- a/src/app.js
  2. +++ b/src/app.js
  3. @@ -2,11 +2,23 @@ import '../assets/styles/app.scss';
  4. import {h, render} from 'preact';
  5. import {Router, Link} from 'preact-router';
  6. +import {useState, useEffect} from 'preact/hooks';
  7. +import {findConferences} from './api/api';
  8. import Home from './pages/home';
  9. import Conference from './pages/conference';
  10. function App() {
  11. + const [conferences, setConferences] = useState(null);
  12. +
  13. + useEffect(() => {
  14. + findConferences().then((conferences) => setConferences(conferences));
  15. + }, []);
  16. +
  17. + if (conferences === null) {
  18. + return <div className="text-center pt-5">Loading...</div>;
  19. + }
  20. +
  21. return (
  22. <div>
  23. <header className="header">
  24. @@ -19,15 +31,17 @@ function App() {
  25. </nav>
  26. <nav className="bg-light border-bottom text-center">
  27. - <Link className="nav-conference" href="/conference/amsterdam2019">
  28. - Amsterdam 2019
  29. - </Link>
  30. + {conferences.map((conference) => (
  31. + <Link className="nav-conference" href={'/conference/'+conference.slug}>
  32. + {conference.city} {conference.year}
  33. + </Link>
  34. + ))}
  35. </nav>
  36. </header>
  37. <Router>
  38. - <Home path="/" />
  39. - <Conference path="/conference/:slug" />
  40. + <Home path="/" conferences={conferences} />
  41. + <Conference path="/conference/:slug" conferences={conferences} />
  42. </Router>
  43. </div>
  44. )
  45. --- a/src/pages/home.js
  46. +++ b/src/pages/home.js
  47. @@ -1,7 +1,28 @@
  48. import {h} from 'preact';
  49. +import {Link} from 'preact-router';
  50. +
  51. +export default function Home({conferences}) {
  52. + if (!conferences) {
  53. + return <div className="p-3 text-center">No conferences yet</div>;
  54. + }
  55. -export default function Home() {
  56. return (
  57. - <div>Home</div>
  58. + <div className="p-3">
  59. + {conferences.map((conference)=> (
  60. + <div className="card border shadow-sm lift mb-3">
  61. + <div className="card-body">
  62. + <div className="card-title">
  63. + <h4 className="font-weight-light">
  64. + {conference.city} {conference.year}
  65. + </h4>
  66. + </div>
  67. +
  68. + <Link className="btn btn-sm btn-blue stretched-link" href={'/conference/'+conference.slug}>
  69. + View
  70. + </Link>
  71. + </div>
  72. + </div>
  73. + ))}
  74. + </div>
  75. );
  76. -};
  77. +}

Finally, Preact Router is passing the “slug” placeholder to the Conference component as a property. Use it to display the proper conference and its comments, again using the API; and adapt the rendering to use the API data:

patch_file

  1. --- a/src/pages/conference.js
  2. +++ b/src/pages/conference.js
  3. @@ -1,7 +1,48 @@
  4. import {h} from 'preact';
  5. +import {findComments} from '../api/api';
  6. +import {useState, useEffect} from 'preact/hooks';
  7. +
  8. +function Comment({comments}) {
  9. + if (comments !== null && comments.length === 0) {
  10. + return <div className="text-center pt-4">No comments yet</div>;
  11. + }
  12. +
  13. + if (!comments) {
  14. + return <div className="text-center pt-4">Loading...</div>;
  15. + }
  16. +
  17. + return (
  18. + <div className="pt-4">
  19. + {comments.map(comment => (
  20. + <div className="shadow border rounded-lg p-3 mb-4">
  21. + <div className="comment-img mr-3">
  22. + {!comment.photoFilename ? '' : (
  23. + <a href={ENV_API_ENDPOINT+'uploads/photos/'+comment.photoFilename} target="_blank">
  24. + <img src={ENV_API_ENDPOINT+'uploads/photos/'+comment.photoFilename} />
  25. + </a>
  26. + )}
  27. + </div>
  28. +
  29. + <h5 className="font-weight-light mt-3 mb-0">{comment.author}</h5>
  30. + <div className="comment-text">{comment.text}</div>
  31. + </div>
  32. + ))}
  33. + </div>
  34. + );
  35. +}
  36. +
  37. +export default function Conference({conferences, slug}) {
  38. + const conference = conferences.find(conference => conference.slug === slug);
  39. + const [comments, setComments] = useState(null);
  40. +
  41. + useEffect(() => {
  42. + findComments(conference).then(comments => setComments(comments));
  43. + }, [slug]);
  44. -export default function Conference() {
  45. return (
  46. - <div>Conference</div>
  47. + <div className="p-3">
  48. + <h4>{conference.city} {conference.year}</h4>
  49. + <Comment comments={comments} />
  50. + </div>
  51. );
  52. -};
  53. +}

The SPA now needs to know the URL to our API, via the API_ENDPOINT environment variable. Set it to the API web server URL (running in the .. directory):

  1. $ API_ENDPOINT=`symfony var:export SYMFONY_PROJECT_DEFAULT_ROUTE_URL --dir=..` yarn encore dev

You could also run in the background now:

  1. $ API_ENDPOINT=`symfony var:export SYMFONY_PROJECT_DEFAULT_ROUTE_URL --dir=..` symfony run -d --watch=webpack.config.js yarn encore dev --watch

And the application in the browser should now work properly:

Step 27: Building an SPA - 图3

Step 27: Building an SPA - 图4

Wow! We now have a fully-functional, SPA with router and real data. We could organize the Preact app further if we want, but it is already working great.

Deploying the SPA in Production

SymfonyCloud allows to deploy multiple applications per project. Adding another application can be done by creating a .symfony.cloud.yaml file in any sub-directory. Create one under spa/ named spa:

.symfony.cloud.yaml

  1. name: spa
  2. type: php:8.0
  3. size: S
  4. build:
  5. flavor: none
  6. web:
  7. commands:
  8. start: sleep
  9. locations:
  10. "/":
  11. root: "public"
  12. index:
  13. - "index.html"
  14. scripts: false
  15. expires: 10m
  16. hooks:
  17. build: |
  18. set -x -e
  19. curl -s https://get.symfony.com/cloud/configurator | (>&2 bash)
  20. (>&2
  21. unset NPM_CONFIG_PREFIX
  22. export NVM_DIR=${SYMFONY_APP_DIR}/.nvm
  23. yarn-install
  24. set +x && . "${SYMFONY_APP_DIR}/.nvm/nvm.sh" && set -x
  25. yarn encore prod
  26. )

Edit the .symfony/routes.yaml file to route the spa. subdomain to the spa application stored in the project root directory:

  1. $ cd ../

patch_file

  1. --- a/.symfony/routes.yaml
  2. +++ b/.symfony/routes.yaml
  3. @@ -1,2 +1,5 @@
  4. +"https://spa.{all}/": { type: upstream, upstream: "spa:http" }
  5. +"http://spa.{all}/": { type: redirect, to: "https://spa.{all}/" }
  6. +
  7. "https://{all}/": { type: upstream, upstream: "varnish:http", cache: { enabled: false } }
  8. "http://{all}/": { type: redirect, to: "https://{all}/" }

Configuring CORS for the SPA

If you deploy the code now, it won’t work as a browser would block the API request. We need to explicitly allow the SPA to access the API. Get the current domain name attached to your application:

  1. $ symfony env:urls --first

Define the CORS_ALLOW_ORIGIN environment variable accordingly:

  1. $ symfony var:set "CORS_ALLOW_ORIGIN=^`symfony env:urls --first | sed 's#/$##' | sed 's#https://#https://spa.#'`$"

If your domain is https://master-5szvwec-hzhac461b3a6o.eu.s5y.io/, the sed calls will convert it to https://spa.master-5szvwec-hzhac461b3a6o.eu.s5y.io.

We also need to set the API_ENDPOINT environment variable:

  1. $ symfony var:set API_ENDPOINT=`symfony env:urls --first`

Commit and deploy:

  1. $ git add .
  2. $ git commit -a -m'Add the SPA application'
  3. $ symfony deploy

Access the SPA in a browser by specifying the application as a flag:

  1. $ symfony open:remote --app=spa

Using Cordova to build a Smartphone Application

Apache Cordova is a tool that builds cross-platform smartphone applications. And good news, it can use the SPA that we have just created.

Let’s install it:

  1. $ cd spa
  2. $ yarn global add cordova

Note

You also need to install the Android SDK. This section only mentions Android, but Cordova works with all mobile platforms, including iOS.

Create the application directory structure:

  1. $ cordova create app

And generate the Android application:

  1. $ cd app
  2. $ cordova platform add android
  3. $ cd ..

That’s all you need. You can now build the production files and move them to Cordova:

  1. $ API_ENDPOINT=`symfony var:export SYMFONY_PROJECT_DEFAULT_ROUTE_URL --dir=..` yarn encore production
  2. $ rm -rf app/www
  3. $ mkdir -p app/www
  4. $ cp -R public/ app/www

Run the application on a smartphone or an emulator:

  1. $ cordova run android

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.