Gatsby Posts

post

Last week, we run into a problem for one of the large Gatsby + ReactJS + Laravel projects in hosting which is hosted with Apache Webserver on Amazon AWS EC2. The problem we were facing was, for some reason, when we reload the Gatsby website, it was giving a 404 error page.

If you open a home page and then a normal visit then the website will fully function, but if you reload the page then it gives an error. And we found it happens when we are using Dynamic routing of React Route in Gatsby as per show in Gatsby documentation here.

Also, what we found, if we test the website build with gatsby serve then it works fine. But while using Apache, it behaves differently and we found that this problem has been faced by lots of people over the internet.

So what we came up with is, we used gatsby serve with an apache proxy. Here is how we did it,

Step 1 - Setup Project

As a first step, clone the project on the server and run a command, gatsby build to create a gatsby build.

Step 2 - Setup PM2 for Gatsby Serve

The next step that we need to do is run gatsby serve. But as you know, we can not run this command directly via console, because as you exit from the console, the command will be terminated.

So we will be using pm2 package, a NodeJS utility that is used to run nodejs apps.

For that, we will need to install pm2 globally. Run the following command to install it,

npm install pm2 -g

You can find other installation ways here if you need.

Once the installation has been done, let's run the gatsby serve command via pm2. For that run the following command from the gatsby project folder,

pm2 start gatsby --name my-web-app -- serve

where my-web-app you can replace with the name of your app.

Once, it's running, try to test it, if it's working correctly by opening the URL http://your-ip-address:9000/. Make sure, port 9000 is opened on your server for traffic.

Step 3 - Configure Apache

Once, gatsby serve is working and tested. The next step is to configure apache to proxy all port 80 traffic to port 9000.

For that, edit your apache conf file (or virtual host conf file), and add the following lines (or configure it to something like the following),

<VirtualHost *:80>
        ServerName my-web-app.infyom.com

        ServerAdmin webmaster@infyom.com

        ProxyRequests On
        ProxyPass / http://localhost:9000/
        ProxyPassReverse / http://localhost:9000/

        ErrorLog ${APACHE_LOG_DIR}/my-web-app.infyom.com.error.log
        CustomLog ${APACHE_LOG_DIR}/my-web-app.log combined

        ......
        # any other options below as per your need
        ......
</VirtualHost>

The next step you need to do is restart your apache server by,

sudo service apache2 restart

And then you can just open the URL https://my-web-app.infyom.com and it should work fine.

Bonus

New Deployment

Whenever you deploy a new code, you again need to run gatsby build and then pm2 restart my-web-app. Then only it will take new changes.

Troubleshooting

Sometimes, we found that we need to restart apache as well after the new deployment. so if you run into any trouble, then make sure to restart apache as well and it should solve the problem.

I hope it may help you to resolve your 404 problem.

July 16, 20213 minutesauthorMitul Golakiya
post

What is a PWA?

A Progressive Web App (PWA) is a hybrid of a regular web page and a mobile application. A PWA combines features offered by most modern browsers with the benefits of the mobile experience. They are built using standard web technologies, including HTML, CSS, and JavaScript. The functionalities include working offline, push notifications, and device hardware access and enabling creating user experiences similar to native applications.

How to make a PWA

Following Below steps

  • Create an app manifest.json file
  • Add it to your base HTML template
  • Create the service worker
  • Serve the service worker on the root of the scope you used in the manifest
  • Add a block to your base HTML template file
  • Site deploy in your server

Create an App Manifest

  • Add the following information in 'manifest.json'
 {
    name: `Name`,
    short_name: `Sort name`,
    start_url: `/`,
    display: `standalone`,
    icon:  `Favicon icon`,
    icons: [
       {
        "src": "icon by size",
        "sizes": "144x144",
        "type": "image/png",
        "purpose": "any"
      },
      {
        "src": "icon by size",
        "sizes": "192x192",
        "type": "image/png",
        "purpose": "maskable"
      },
      {
        "src": "icon by size",
        "sizes": "512x512",
        "type": "image/png",
        "purpose": "maskable"
      }
    ],
  theme_color: `Theme color`,
  background_color: `Background color`,
  ]
 }
  • Manifest.json file in add this type of code including name, short_name, start_url, display, icon, icons, theme_color, background_color.

Add the Manifest to Your Base HTML Template

  • Add the following line in yore 'index' file

Create offline.html as an Alias to index.html

By default, the service worker code below will render /offline.html instead of any resource it can't fetch while offline. Create a file at /offline.html to give your user a more helpful error message, explaining that this data isn't cached and the user is offline.

Create a Service Worker

  • Create one file in yore root (sw.js)
  • Link the sw.js file in the body tag

We have created some pages like

  1. Home page (/)
  2. Blog page (/blog)
  3. Contact information (/contact)
  4. Resume (/resume)
  5. offline.html
  • Add the code in your sw.js file
self.addEventListener("install", function(event) {
   event.waitUntil(preLoad());
});

 var preLoad = function(){
  return caches.open("offline").then(function(cache) {
    return cache.addAll(["/blog/", "/blog", "/", "/contact", 
 "/resume", "/offline.html"]);
    });
 };

 self.addEventListener("fetch", function(event) { event.respondWith(checkResponse(event.request).catch(function() 
  {
     return returnFromCache(event.request);
   }));
   event.waitUntil(addToCache(event.request));
  });

  var checkResponse = function(request){
   return new Promise(function(fulfill, reject) {
     fetch(request).then(function(response){
       if(response.status !== 404) {
         fulfill(response);
       } else {
         reject();
       }
     }, reject);
   });
  };

  var addToCache = function(request){
   return caches.open("offline").then(function (cache) {
     return fetch(request).then(function (response) {
       console.log(response.url + " was cached");
       return cache.put(request, response);
     });
   });
  };

  var returnFromCache = function(request){
   return caches.open("offline").then(function (cache) {
     return cache.match(request).then(function (matching) {
      if(!matching || matching.status == 404) {
        return cache.match("offline.html");
      } else {
        return matching;
      }
     });
   });
  };
  • Servicer worker file add your body tag

load the service worker file in

 

Last step

  • Deploy code in yore live site
  • Create lighthouse report and check PWA
July 28, 20214 minutesauthorVatsal Sakariya
post

Today I’m going to show you 5 easy ways to create a backlink for a website. If you do apply this method I'm sure to get a quality high-domain authorities website backlink.

At this time, all people want their website position 1st in google ranking.

If you want to rank your website in google 1st, create a backlink from a high authority site.

So let’s get started with 5 easy ways to create a backlink for a website.

1. Article Submission

What is article submission?

Article submission is the process to submit your article to high-quality websites or directories to improve SEO ranking and get traffic to websites.

Some free sites are available for submitting an article.

Article submission is one of the easy ways to create backlinks for a website.

Why Article submission is important from a backlink point of view?

Article submission is an effective off-page SEO technique.

Using Article submission you can get quality backlinks from high domain authorities website which use to get traffic to your website and improve SEO ranking.

How to submit an article to a free article submission site?

  • Check article submission site DA & PA.
  • Register on the article submission site.
  • Choose the category of your article.
  • Include your article or website link in the author’s description box. It’s the most important step.
  • Submit your article
  • Check your article is published or not.

Here is some site to submit Free Article

2. Quora Answering

What is Quora Answering?

Quora answering is the site where users can ask questions related to their queries. And people can answer user’s query answer in quora.

What is the DA of quora?

DA: 93

Why Quora is useful for backlinks?

People can answer user’s queries in quora. And put their website link or article post link.

It’s a type of backlink. When users click on that link they redirect to your site.

Quora is an easy way to create a backlink for your website.

Using Quora you can create a high-quality backlink.

Quora backlink is also affected traffic to your website means increased traffic to your website and improve your SEO ranking using create a backlink from quora.

Guideline to create a backlink on quora

  • Do not create a backlink
  • First some answers to user’s queries
  • The recommended way is to answer 5 user’s queries and creates links to only a maximum of two of them.
  • If you create all answers with your link then quora can ban you.

How to create a backlink from quora?

  • Create an account on quora
  • Answer user’s queries
  • Create a link to your article.
  • It’s a Nofollow backlink for your website.

    All quora backlink is nofollow means It’s used to increase traffic for your website but google crawler can not read backlink because it’s nofollow.

3. Social Bookmarking

What is social bookmarking?

Social bookmarking is sites where a user submits their blog post, article, videos, etc.

Why use social bookmarking for SMM?

Social bookmarking sites where social media marketing managers find posts to their relevant topic. It’s Important to reach our posts through social media to more people and get traffic from them.

How to use a social bookmarking site to create backlinks?

  • Create an account
  • Submit your site
  • Create a backlink

Here are some sites of social bookmarking

It’s an easy way to create a backlink for your website. In social bookmarking sites some backlinks are dofollow and some backlinks are nofollow.

4. Directory Submission

What is directory submission?

Directory submission where you can submit your site URL and details about your website to increase link building for your site.

A web directory is a kind of a website that has some categories, sub-categories are there. You can submit your site to a category of your niche.

Why Directory submission is important for link building?

Using directory submission you can create high-quality backlinks from some high-domain authorities. It’s useful to get more traffic to your website and improve SEO ranking.

Types of Web Directory

  • Paid and featured listing
  • Regular link with reciprocal link
  • Free and regular listing

How to use the Directory Submission site to create backlinks?

  • Create an account
  • Select a free and regular listing option
  • Submit detail about your website
  • Create backlinks

Here are some sites of social bookmarking

5. Ping Submission

Here are some sites of social bookmarking

Ping Submission is a mechanism of sending autogenerated notifications to google spider.

It is one type of SEO tool. Where you can submit your blog post or website to get backlinks.

What are the benefits of Ping submission

  • Improve SEO ranking
  • Useful for site indexing
  • Easy ways to create backlinks
  • Also, use for improving search engine result pages

How to get backlinks using ping submission?

  • Create an account on the ping submission site
  • Submit a blog post to the relevant category
  • Get a backlink
  • Not submit more than 3 same URLs on one ping submission site

Ping Submission Site

Conclusion:

In this topic 5 easy ways to create a backlink for a website, if you read the whole blog post you have an answer on how to create backlinks. I hope your problem will be solved on this topic.

July 24, 20214 minutesauthorMilan Gangani
post

We have recently developed a site into the gatsby. We want to add Google Analytics to the website.

So, this is the way we implemented Google Analytics in the Gatsby site.

Use Gatsby Google GTag Plugin

Gatsby has a plugin gatsby-plugin-google-gtag that be used to easily add Google Global Site Tag to your Gatsby site.

Install the package by running the following command:

npm i gatsby-plugin-google-gtag --save

Configuration

Once the installation is complete, you can now add this plugin to your gatsby-config.js:

Configure trackingIds and other options. Add this into the plugins array. Like,

module.exports = {
  // ...
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
              // You can add multiple tracking ids and a pageview event will be fired for all of them.
              trackingIds: [
                "GA-TRACKING_ID", // Google Analytics / GA
                "AW-CONVERSION_ID", // Google Ads / Adwords / AW
                "DC-FLOODIGHT_ID", // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager)
              ],
              // This object gets passed directly to the gtag config command
              // This config will be shared across all trackingIds
              gtagConfig: {
                optimize_id: "OPT_CONTAINER_ID",
                anonymize_ip: true,
                cookie_expires: 0,
              },
              // This object is used for configuration specific to this plugin
              pluginConfig: {
                // Puts tracking script in the head instead of the body
                head: false,
                // Setting this parameter is also optional
                respectDNT: true,
                // Avoids sending pageview hits from custom paths
                exclude: ["/preview/**", "/do-not-track/me/too/"],
              },
      },
    },
  ],
}

This plugin automatically sends a “pageview” event to all products given as “trackingIds” on every Gatsby's route change.

If you want to call a custom event you have access to window.gtag where you can call an event for all products.

Check out this code.

typeof window !== "undefined" && window.gtag("event", "click", { ...data })

NOTE: This plugin only works in production mode! To test your Global Site Tag is installed and 

You need to run the following command for firing events correctly.

gatsby build && gatsby serve

If you need to exclude any path from the tracking system, you can add one or more to this optional array.

November 22, 20202 minutesauthorShailesh Ladumor
post

We have recently developed a site into the gatsby.

We have a blog site and hosted it on a different domain but now we want to move to one place at our main site. now, we have challenges for displaying dynamic blogs on the gatsby site.

Finally, I found that gatsby provides support to render dynamic blogs as a static page. when build created that time fetch the blogs from the server and create a static page for all the blogs.

Gatsby is a very good platform and manages such a kind of thing easily.

So, I will show you how to create static pages from the API response into the Gatsby site.

Here are the steps you need to follow correctly.

Steps 1

Create a one blog file where you want to load a blog in your design.

For an ex. I created a file `blog/index.js` inside the component directory and the code looks like this,


Steps 2

Open a file `gatsby-node.js`

Declare the const for the API URL at the beginning of the file.

const blogURL = 'http://blog-api.com/api/posts';

We need to create an instance of the  `node-fetch` for fetching a data from API server.

const fetch = require(`node-fetch`);
Import the path for a resolve the page while creating a static page.
const path = require('path');
See the example how to create a static page from APIs. code look's like,
exports.createPages = (async ({graphql, actions}) => {
    const blogs = await fetch(blogURL);
    blogs.data.forEach((blog) => {
        createPage({
            path: 'blog/' + blog.slug,
            component: path.resolve(`./src/components/blog/index.js`),
            context: {
                // Data passed to context is available
                // in page queries as GraphQL variables.
                slug: blog.slug,
                blog: blog,
            },
        })
    })
Now we are done, and you can access blogpage via slug.


November 12, 20201 minuteauthorShailesh Ladumor
post
We are recently developed a site into the gatsby. basically contact us feature is common in all website.
and we are implementing Mailchimp because it's a very popular platform in email market.

So, I will show you how to setup a Mailchimp in the Gatsby site.

## Using gatsby-source-mailchimp

Use your Mailchimp API key to download your campaigns into Gatsby’s GraphQL data layer!

Install the package by running the following command: `npm i gatsby-source-mailchimp --save`

### How to configure
Once the installation is complete, you can now add this plugin to your gatsby-config.js, like so:

Configure mailchimp Key and add this {resolve: `gatsby-source-mailchimp`} into the plugins array. code looks like

```
module.exports = {
  // ...
  plugins: [
    {
      resolve: 'gatsby-source-mailchimp',
      options: {
        // Avoid including your key directly in your file.
        // Instead, opt for adding them to .env files for extra
        // security ;)
        key: 'asd712jdas90122jdas90122jkadsd1-usXX',
        rootURL: 'https://usXX.api.mailchimp.com/3.0',
      },
    },
  ],
  // ...
}
```

Above is the minimal configuration required to have it work. By default,
This plugin was made out of a specific necessity, so it doesn't cover all of Mailchimp’s data sources, focusing only on campaigns.

this plugin are provide few options. you can refer here.

## Using `.env` variables to hide your key
If you don’t want to attach your API key to the repo, you can easily store it in .env files by doing the following:

```
// In your .env file
MAILCHIMP_KEY = 'asd712jdas90122jdas90122jkadsd1-usXX';
```

```
// In your gatsby-config.js file
require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
});

module.exports = {
  // ...
  plugins: [
    {
      resolve: 'gatsby-source-mailchimp',
      options: {
        key: process.env.MAILCHIMP_KEY,
        rootURL: 'https://usXX.api.mailchimp.com/3.0',
        // ...
      },
    },
  ],
  // ...
};
```


October 31, 20201 minuteauthorShailesh Ladumor
post
We are adding a sitemap in our all site pages for making sure search engines (such as Google) can find and crawl them all. 

So, I will show you how to set a sitemap on the Gatsby site.

To generate an XML sitemap, you will use the gatsby-plugin-sitemap package.

Install the package by running the following command: npm install gatsby-plugin-sitemap


How to configure

Once the installation is complete, you can now add this plugin to your gatsby-config.js, like so:

Configure siteUrl and add this {resolve: `gatsby-plugin-sitemap`} into the plugins array. code looks like


module.exports = {
  siteMetadata: {
    title: `InfyOm Technologies`,
    description: `InfyOm Technologies`,
    keyword: `InfyOm Technologies`,
    author: `@gatsbyjs`,
    siteUrl: `http://infyom.com`
  },
  flags: {
    PRESERVE_WEBPACK_CACHE: true,
  },
  plugins: [
    {resolve: `gatsby-plugin-sitemap`},
  ],}

Above is the minimal configuration required to have it work. By default, the generated sitemap will include all of your site’s pages.
you can exclude a path using the exclude option. you need to configure it

  • output (string) The file path and name. Defaults to /sitemap.xml.
  • exclude (array of strings) An array of paths to exclude from the sitemap.
code looks like,

module.exports = {
  siteMetadata: {
    title: `InfyOm Technologies`,
    description: `InfyOm Technologies`,
    keyword: `InfyOm Technologies`,
    author: `@gatsbyjs`,
    siteUrl: `http://infyom.com`
  },
  flags: {
    PRESERVE_WEBPACK_CACHE: true,
  },
  plugins: [
    {
	resolve: `gatsby-plugin-sitemap`,
    options: {
      output: `/some-other-sitemap.xml`,
        exclude: [`/category/*`, `/path/to/page`],
		}
	},
  ],
}
NOTE: This plugin only generates an output when run in production mode! To test your sitemap, run: gatsby build && gatsby serve

now we are done and open sitemap using your domain. for ex. https://xxx.com/sitemap.xml










September 28, 20201 minuteauthorShailesh Ladumor