A starter template for server-side authentication of Gatsby static-site content with Node.js and Express using Auth0 (deployable to Heroku).
This does not use any client-only routes in Gatsby.
Based off of Auth0 + Node.js on Heroku.
Illustration of problem area for gatsbyjs/gatsby#20745.
Setup for Auth0 is fast and easy:
- Sign up for a free account at Auth0, go to the Dashboard and hit the Create button:
- Create an application with the "Regular Web Application" template:
- Go to the Settings tab and make a note of the Domain, Client ID and Client Secret. This information will be used for the Heroku setup.
Create a Heroku account at Heroku - Sign up, and then click on this button:
This will set up a new application on your Heroku account using this repo as a template.
Choose your own app name, and use it in the AUTH0_CALLBACK_URL
field.
During setup you'll also be asked for some other environment variables, which is the information that we noted earlier in the Auth0 setup:
After Heroku is set up, return to the Auth0 Settings page and enter the URL in the Allowed urls (replace YOUR-APP with the App name that you chose):
- Enter your Allowed Callback URLs:
http://localhost:3000/callback,https://YOUR-APP.herokuapp.com/callback
- Enter your Allowed Logout URLs:
http://localhost:3000,https://YOUR-APP.herokuapp.com
It should appear like this:
Now everything should be set up! If you visit the application URL in a browser, Auth0 will ask for you to log in to the application:
After logging in, the Gatsby default starter homepage will be displayed:
If there are any messages passed through the query string in the URL by Auth0, they will be displayed:
There is also rudimentary access control set up for Gatsby static pages in the Express server. It is configured to deny requests for any assets from the Gatsby website src/pages/page-2.mdx
page:
This access control serves as a proof of concept - hopefully new tools will become available for Gatsby to improve this workflow:
Finally, if the user visits any file that doesn't exist in the gatsby-website/public
folder, the Gatsby 404 page will be displayed:
Log out of the app by visiting the /logout
route.
If you want to run the server locally, you can do this as follows:
Install the dependencies.
npm install
Copy the contents of .env.example
to a new file called .env
and replace the values for AUTH0_DOMAIN
, AUTH0_CLIENT_ID
, and AUTH0_CLIENT_SECRET
with your Auth0 information (from the Settings page). Replace EXPRESS_SESSION_SECRET
with a secret to be used for the session.
# Copy configuration to replace with your own information
cp .env.example .env
Run the app.
npm start
The app will be served at localhost:3000
.