Gatsby/Wordpress - .env credentials not working - wordpress

I am working with the gatsby-source-wordpress plugin
If I hard code my API keys/secret into my Gatsby.config, everything works fine, but I want to add these as .env variables so that I can .gitignore for deployment, and this is where things are breaking.
At the root of my directory, I have a .env file which looks like this
CLIENT_SECRET=10987654321
CLIENT_ID=123456
USER=secret#secret.com
PASS=mypassword1
I'm then try to access these in gatsby.config, like this
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`
});
module.exports = {
siteMetadata: {
title: 'Gatsby Default Starter',
},
plugins: [
{
resolve: 'gatsby-source-wordpress',
options: {
baseUrl: 'myurl.com',
protocol: 'http',
hostingWPCOM: true,
useACF: false,
auth: {
wpcom_app_clientSecret: `${process.env.CLIENT_SECRET}`,
wpcom_app_clientId: `${process.env.CLIENT_ID}`,
wpcom_user: `${process.env.USER}`,
wpcom_pass: `${process.env.PASS}`,
},
},
},
{
resolve: `gatsby-plugin-emotion`,
},
'gatsby-plugin-react-helmet',
{
resolve: `gatsby-plugin-manifest`,
options: {
name: 'gatsby-starter-default',
short_name: 'starter',
start_url: '/',
background_color: '#663399',
theme_color: '#663399',
display: 'minimal-ui',
icon: 'src/images/gatsby-icon.png', // This path is
relative to the root of the site.
},
},
'gatsby-plugin-offline',
],
}
which is returning the following errors when I run either gatsby develop or gatsby build
source and transform nodesThe server response was "400 Bad Request"
source and transform nodesThe server response was "403 Forbidden"
Inner exception message : "User cannot access this private blog."
No routes to fetch. Ending.
So, the issue is the .env variables don't seem to be pulling through properly, but I can't see a reason why they wouldn't be? Is there anything I've missed in setting this up?

Gatsby doesn't know which plugin you mean (see How to use) and your overall syntax is wrong. The plugins is an array for example.
module.exports = {
plugins: [
{
resolve: "gatsby-source-wordpress",
options: {
auth: {
wpcom_app_clientSecret: process.env.CLIENT_SECRET,
wpcom_app_clientId: process.env.CLIENT_ID,
wpcom_user: process.env.USER,
wpcom_pass: process.env.PASS,
}
}
}
]
}
This should work assuming that you also define the other necessary fields mentioned in the README.

Related

Flash of unstyled content in Gatsby when using global style sheet

I am working on a gatsby project where everything is working fine, except for when I load any page of the website as there is a flash of unstyled content for like a second. The issue persists in all the pages and my research on fixing this issue revealed this to be a persisting issue when working with styled-components. My project does not use styled components as there is one global style sheet that is shared across the project as the style sheet is loaded in the gatsby-browser.js.
code in the config below. Can anyone assist me here?
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`
});
module.exports = {
siteMetadata: {
title: 'name of site',
siteUrl: `https://lffff.com`,
description: `some description.`,
author: 'name',
image: 'image link'
},
pathPrefix: '/v2',
plugins: [
'gatsby-transformer-sharp',
'gatsby-plugin-react-helmet',
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images/`
}
},
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN
}
},
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /assets/
}
}
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `GatsbyJS`,
short_name: `GatsbyJS`,
start_url: `/`,
display: `standalone`,
icon: 'src/images/5f8e0f3ace9452d1a7fbe65b_LP_Logo_Square.png'
}
}
]
};
this is what is in gatsby-browser.js
import './src/styles/globalStyles.css';
You are using prefixed paths at:
pathPrefix: '/v2',
In development (gatsby develop) paths don't need to be prefixed, however, during the build and server process (gatsby build && gatsby server) it's a needed specification
If you are building a path manually, you can use withPrefix helper function that prepends your path prefix in production.
Change your build and serve commands to:
gatsby build --prefix-paths
And:
gatsby serve --prefix-paths
If you are not using the pathPrefix, just remove it from your configuration and keep your commands as at the beginning.

Login to Wordpress with Gatsby

I'm trying to make a static website using Wordpress and Gatsby everything works fine locally but when I try to use it on a staging site I get this error :
Path: /wp-json
The server response was "401 Unauthorized"
Inner exception message: "You are not currently logged in."
ERROR #11321 PLUGIN
So is there a way to give Gatsby access to my Wordpress website using my credentials ?
My gatsby-config.js :
module.exports = {
siteMetadata: {
},
plugins: [
{
resolve: `gatsby-source-wordpress`,
options: {
baseUrl: `web-staging.******.io`,
protocol: `https`,
hostingWPCOM: false,
useACF: false,
},
},
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
],
}
See the options for the plugin, specifically auth:
auth: {
// If auth.user and auth.pass are filled, then the source plugin will be allowed
// to access endpoints that are protected with .htaccess.
htaccess_user: "your-htaccess-username",
htaccess_pass: "your-htaccess-password",

How to use AWS Amplify env vars in gatsby-config.js?

I am building an app with GatsbyJS. I am using environment variables in my gatsby-config.js. GatsbyJS app builds fine locally, by using .env.* files. However, when building from AWS Amplify it complains about an invalid value retrieved from environment variables. Indeed, it seems that when using process.env.MY_VAR inside gatsby-config.js the value retrieved is encrypted (as per AWSAmplify docs).
I tried with hardcoding the value of the env. var to confirm that encryption was the problem.
The error that I am getting is:
TypeError [ERR_INVALID_URL]: Invalid URL: 6fbaeed85a68.
Which clearly indicates that the value retrieved from process.env.HOSTNAME is 6fbaeed85a68 and not the actual value that I provided in AWS Amplify web's interface.
Below is my gatsby-js.config:
const path = require(`path`);
const queries = require('./src/utils/algolia');
const feedOptions = require('./src/utils/feed');
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
siteMetadata: {
siteUrl: new URL(process.env.HOSTNAME).href,
title: `APP_TITLE`,
},
plugins: [
{
resolve: `gatsby-source-kentico-cloud`,
options: {
deliveryClientConfig: {
projectId: process.env.KENTICO_PROJECT_ID,
},
languageCodenames: process.env.KENTICO_LANGUAGES.split(';'),
},
},
{
resolve: `gatsby-plugin-algolia`,
options: {
appId: process.env.GATSBY_ALGOLIA_APP_ID,
apiKey: process.env.ALGOLIA_ADMIN_KEY,
queries,
chunkSize: 10000,
},
},
`gatsby-plugin-react-helmet`,
`gatsby-plugin-sitemap`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `APP_NAME`,
short_name: `APP_SHORT_NAME`,
start_url: `/`,
background_color: `#dbdcd1`,
theme_color: `#1ad2eb`,
display: `standalone`,
icon: `src/images/logo-simple-transp-square-260x260.png`,
include_favicon: true,
},
},
`gatsby-plugin-offline`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-sass`,
options: {
includePaths: ['src/styles/_variables'],
},
},
{
resolve: 'gatsby-plugin-mailchimp',
options: {
endpoint: process.env.MAILCHIMP_ENDPOINT,
},
},
{
resolve: 'gatsby-plugin-transition-link',
options: {
layout: require.resolve(`./src/layout`),
},
},
{
resolve: `gatsby-plugin-feed`,
options: feedOptions,
},
{
resolve: `gatsby-plugin-google-tagmanager`,
options: {
id: process.env.GTM_CODE,
includeInDevelopment: false,
},
},
],
};
I don't understand how I am supposed to retrieve env vars. Any help would be greatly appreciated.
When adding environment variables to AWS Amplify App under App Setting -> Environment Variables, just prefix GATSBY_ to all your environment variable names. Remember to change your code to use the new names.
Adding GATSBY_ makes env variables accessible to browser javascript.
Read more about it in the official documentation.

How to integrate WordPress into Webpack?

I developed a website front-end using HTML/CSS, JavaScript and Sass or Scss. I used NPM.
I need to put that website into WordPress. I already installed WordPress and put that folder with all my assets(HTML/CSS, JS, Sass etc..) into theme folder.
Now, what do I do now? How do I connect all of this?
I know it's possible because I have worked on a site like this before at work, but not sure how to do it from the ground up.
Webpack -> WordPress. I will watch the files with NPM or webpack, but the hosting will be doing with MAMP - that's how I did it at work anyways.
What should I do?
This is the website code if anything: https://github.com/AurelianSpodarec/lovetocodefinal
PS, no WordPress API or any stuff like that, but just as I wrote above.
I found a solution to this.
It's simple. You need to compile everything and put it in the folders that will be used by WordPress and do WordPress magic to get the styles with functions.
I have made this here: https://github.com/AurelianSpodarec/Webpack-to-WordPress-Starting-Template
It's not perfect, but a good starting point for those who are looking on using Webpack with WordPress.
Old Question, but just had the same one myself. I just built a light Wordpress-Webpack starter. You can use it to build Wordpress-Themes and it will build Scss and copy PHP etc. into the destination of your Themes. It uses Browsersync for easier development. You have complete separation of dev and build :) Maybe this can still help in future. Regards, Fabian
Link: https://github.com/fabiankuhn/webpack-wordpress
Extract from Main Build config (Paths):
const themeName = 'test-theme'
const themePath = '/Users/<Username>/<repos>/Test/webpack/wordpress/wp-content/themes'
/*
* Main Config
*/
module.exports = {
entry: './webpack-entry.js', // Main Entry: Is included in functions.php
output: {
filename: 'main.js', // Is included in functions.php
// Set Path of Wordpress Themes ('.../wp-content/themes') as absolute Path
path: themePath + '/' + themeName + '/assets',
},
Extract from Wordpress webpack config:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
// This Config Exports the FIles with Source Maps for Wordpress Development
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map', // Use Source-Maps for Debug
plugins: [
// Plugin to Reload Browser According to Proxy 127.0.0.1:8080 (Wordpress PHP)
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: '127.0.0.1:8080',
files: [
{
match: [
'**/*.php',
'**/*.js',
'**/*.css',
],
},
],
notify: false,
},
{
reload: true,
}),
// Extract CSS
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
// Copy all Files to Entry Output Path except Github, Webpack and
// Original Sources (Before Webpack Processing)
new CopyPlugin([
{
from: '../',
to: '../',
ignore: [
'_webpack/**',
'assets/**',
'.git/**',
],
},
]),
],
module: {
rules: [
{
// Listen for Sass and CSS
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
},
},
// Source Map shows Path in Chrome for Testing
{ loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
],
},
});

Is this the right way to get lite-server to recognize the "server.index" override in bs-config.js?

lite-server seems to be ignoring my attempt to override the default index.
I have bs-config.json:
{
"server": {
"baseDir": "src",
"index": "/index.3.html",
"routes": {
"/node_modules": "node_modules"
}
}
}
I am using lite-server version 2.3.0, like this:
> lite-server -c=bs-config.json
browser-sync config **
{ injectChanges: false,
files: [ './**/*.{html,htm,css,js}' ],
watchOptions: { ignored: 'node_modules' },
server:
{ baseDir: 'src',
middleware: [ [Function], [Function] ],
directory: true,
index: '/index.3.html',
routes: { '/node_modules': 'node_modules'
}
}
}
In the console log output above, it recognizes the bs-config.json index default of "index.3.html", however, when the browser requests "GET http://localhost", the console shows it is trying to serve index.html instead of index.3.html.
[Browsersync] Serving files from: src
[Browsersync] Watching files...
17.09.04 22:35:51 404 GET /index.html
I have also tried supplying bs-config.js:
"use strict";
module.exports = {
"server": {
"baseDir": "src",
index: "i/index.3.html",
"directory":true,
"routes": {
"/node_modules": "node_modules"
}
// middleware,: {
// // overrides the second middleware default with new settings
// 1: require('connect-history-api-fallback')({index: '/index.3.html', verbose: true})
// }
}
}
and running lite-server with:
> lite-server -c=bs-config.js
but the behavior is the same.
Question: how do I override bs-config's server.index for lite-server?
lite-server's config-default.js sets index in it's 2nd middleware "fallback" function. This seems to be overring bs-config setting.
So the solution seems to be, override the middleware to set index as desired.
bs-config.js:
module.exports = {
"server": {
"baseDir": "src",
"routes": {
"/node_modules": "node_modules"
},
middleware: {
// overrides the second middleware default with new settings
1: require('connect-history-api-fallback')({
index: '/index.3.html',
htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] // systemjs workaround})
}
}
}
Notes:
1. If a future version of lite-server changes it's default-config's middleware to put the index fallback in a different index position of the middleware function array, or to set different response headers, then this bs-config solution will need to be changed accordingly.
references:
Browserync Docs: https://browsersync.io/docs/options
lite-server: https://github.com/johnpapa/lite-server

Resources