mysqli_num_rows error boolean given

My site use to work fine. But today for some reason pages with mysqli_num_rows takes a very long time to load. I can visit the page but it takes a long time to load. When it loads there are no errors but the error file in the root directory have the following error:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

There is no problem with my internet connection because other pages load fast and do not send reports to the error file. This is my first time encountring this problem.
Here is the code for the error line:

function fetch_rows($sql){

    global $con;

    $q = mysqli_query($con, $sql);
    return mysqli_num_rows($q);

}

I have tested the query on PhpMyAdmin and it works fine. But for some reason it takes time to load. I have even checked if the database has a lot of records, but it doesn't I have also emptied it.

Have any of you ran into the same error. Or understands the problem?

Thanks

Is Web Design Easier or Harder Than it was 10 Years Ago?

Is it harder or easier to build a website now than 10 years ago? Has the bar gone up or down? I don't have any data for you, but I can shell out some loosey-goosey opinions.

HTML

HTML5 was the only big HTML change in the last decade, and it wasn't particularly dramatic. It's cool it's the looser variant (instead of getting XHTML3 or something). More compatible this way. Maybe I'll close my <br /> and maybe I <br> won't. Having better semantic tags (e.g. <article>) is great. Input types are wonderful. But none of this pushes HTML to be significantly easier or harder.

Same.

CSS

CSS has gotten easier. We use way fewer "hacks" all the time. I can literally feel it. The CSS we write today feels so intentional and direct. 10 years ago I feel like every other element had some kind of weird hack on it, and today, almost none. If CSS feels any harder, I'd wager it's because the sites we're building are bigger and more complex so the styling systems for them need to be all the more robust and the dangers of getting it wrong more stark.

Easier.

JavaScript

I'm sure there are strong arguments to be made both ways here. The language, perhaps, with all its recent syntactic innovation... perhaps easier. But what JavaScript is being asked to do, and what we're doing with it, is so astronomically larger that more difficulty comes along for the ride. It's similar to CSS in that way, but even more pronounced since we're not just doing what we were before on a new scale; we're building entire interfaces with the language in a way we just weren't before.

Harder.

Domains

I mention this one because it's such a crucial step in any given person's ability to go from zero to actually having a website.

I don't think buying a domain name is any easier. Domain names are a commodity market, so the companies selling you them are selling you them for some other reason, meaning the incentive is very high for them to push other products on you. For someone entirely green, I can imagine the confusion is either high or they don't know enough for the confusion to settle in yet. Do I buy it through this page builder thing? Do I have to buy it through this page builder thing? Do I need the WHOIS protection? Oh god, what even is DNS? I guess I do want email, right? Or is that like some weird special hosted email? Ughjakd. I'm gonna call it a wash. Nothing has made this any easier or harder in a decade.

Same.

Hosting

There is so much money in hosting it kind of blows my mind that we don't see deeper innovation here. I might argue it's a little easier these days. But commodity low-end hosting isn't terribly different or being any more or less helpful than it was a decade ago. We're still largely stringing together our own bespoke build and deployment processes like we were 10 years ago.

Large-scale stuff might have seen a lot of innovation, a la AWS, but nobody is going to argue that stuff is anywhere near easy.

The most innovation we've seen is from companies like Netlify and Zeit who are looking at the developer experience wholistically from helping you run things locally, to testing builds in staging, to immutable deploys. I'd love to see all hosting companies realize that every single one of their customers needs to get their code onto their platforms and they have a massive opportunity to help us do that directly.

Slightly easier.

How people actually do it

I like thinking about HTML, CSS, and JavaScript. But of course, precious few people actually start with those technologies to build actual websites from scratch. Really they end up being treated as underlying technologies you dabble in amongst a slew of other tech.

You can build a website from just an index.html file. I'd argue more people should. But people reach for more "complete" solutions and customize from there. I know I did. The first websites I ever created were WordPress because it was a whole website in a box (with its own struggles) and I customized it. People still do that today, probably more now than 10 years ago, and I don't feel like it's significantly easier or harder. Or they reach for something familiar. I made a one-page index.html site not long ago, only to have it picked up by another developer who turned it into a create-react-app site but otherwise changed nothing. They just didn't know how to work on it without React.

Or they use WordPress.com, or Squarespace, or Wix, or Shopify, or BigCommerce, or you know what I mean. This isn't about what people can do, it's about what people do do. And for most people, these apps significantly lower the bar of creating a website.

So, for the average person, is it easier or harder to go from zero to having some kind of website?

Much easier.

Can people actually do it?

If we're talking about creating from scratch, it's interesting to see who feels like they even hold those keys anymore. The whole idea for this post came from a conversation I had with someone who has been a front-end developer and was asked to build a website by a friend. They declined because they didn't know how.

Some part of that doesn't surprise me. As I write, the world is awfully full of React-specific developers working on huge sites (partially due to boot camps, partially due to market demand). They understand that very specific ecosystem and are perfectly productive within it, but don't have a wider understanding of how it all comes together to make the complete site.

Specialists are specialists!

Another part of me is surprised. You know an index.html file with "Hello, World!" in it can be a website, right? Even React devs are generally highly aware of create-react-app and how that scaffolds out a ready-to-rock site. Tools like Stackbit slap together a JAMstack site for you that can go anywhere. For developers, it seems to be going from zero to website is a heck of a lot easier these days.

Much easier.

The post Is Web Design Easier or Harder Than it was 10 Years Ago? appeared first on CSS-Tricks.

Clips from my DEV AMA

I recently did an AMA over on DEV. Just taking the opportunity to port over some answers here like a good indiewebber.

If you were starting out as a front end dev in 2020, what would you say is the first thing you would learn and why?

You need to put yourself in a position where it's your job to create and take care of a website. Even if that feels like a stretch for you early on. Get the domain, get the website on the public internet. Put your name on it. Now you've given yourself stakes, and you'll learn technology because you must make your ideas come to life.

For me, 650 years ago, that was putting up a website for the ol' college band. We needed a website! That sounded like fun to me, and I managed to struggle through buying a domain, hosting, and putting up a WordPress website. Then, over time, I learned front-end web technologies because I wanted to change up the design, change up the templates, add cool features, etc.

Get yourself a project and learn through the project.

How do you determine what you want to turn into a blog post and what you leave as a simple Tweet?

I usually won't avoid the tweet. The tweet is usually a good proving ground for the blog post anyway. If nobody cared, eh, maybe not that good of a post. If it does get good engagement, it's like the conversation around it is useful in the creation of the blog post. Plus, tweets are so easy to kick out the door. Blog posts, for me, on purpose, have a longer schedule that includes editing and scheduling and such.

Here's an example tweet. Just a silly little UI experiment. I didn't feel like waiting to blog about it to drop the demo. But from the Twitter thread, I got some interesting technical feedback, info about what parts people were most suprised by, and some other related ideas. That will, hopefully, lead to a much more robust blog post.

I even treat DEV like that, honestly. I wrote this blog post reaction quickly here, but then refined it for my own blog with some of the feedback.

Do you have a favorite CSS-Trick, where you were just like "wow"?

I think "scroll shadows" in CSS is one of my favorite CSS tricks of all time. It's originally by Roman Komarov, but explained and improved by Lea Verou. I saw a tool the other day around the idea by Stefan Judis.

It's a real mind-bender involving four-layered gradient backgrounds, each positioned, sized, and colored differently, and then behaviorally different regarding scrolling.

It's not just a neat trick because it has real UX implications. Showing a shadow of where you can scroll is important UX. Consider this story of a recent design update in iOS that led to complete confusion around UI actions hidden behind a place you could scroll to, but had zero affordance on how to get there. (Happens to me all the time in Spotify, for the record.)

What would be your top 3 pieces of quick advice for developers trying to follow a similar path to growing their influence and exposure?

I think writing is literally the only way.

I can't think of a developer with influence who has that influence for anything other than writing. Or if it's not writing, then it's a YouTube channel or some other form of creating public stuff.

How much do you see yourself personally playing with Houdini APIs as they are released? Which API are you most excited about (Painting, Layout, Typed OM, ...)?

This super-low level stuff sometimes feels over my head. It's hard for me to picture the industry implications of stuff like this just by looking at specs, ya know?

To me, it seems the Layout API has the most powerful potential.

What I'm imagining right now is that Houdini doesn't affect normal day-to-day front-end developers like me that much. I won't be writing much Houdini code. But I'll use fancy things that other people create, because it does something useful for me. Just like most people don't write their own libraries or have published npm packages — they just use them.

It's fun to be wow'd by Houdini. If anyone is looking for that, make sure to look at Vincent De Oliveira's showcase website.

What is your favorite thing about working at CodePen and/or CSS-Tricks?

You know what I really like? I like getting into the office every day and having a pretty decent amount of freedom of what I'm going to do that day. I'll probably have meetings. I'll probably have some stuff on the ol' calendar. I'll probably have some team expectations I'm trying to meet. But I also usually have plenty of time to pursue things that are interesting to me at the moment.

Sometimes I'm in the moment to drill through some emails. Sometimes I want to tinker with some demo that sounds like fun. Sometimes I want to write up a thought or record a video. Sometimes I want to plan something out or document something. Sometimes I want to talk something out with other people or do some pair programming.

I'm fortunate that I'm the boss (lol) and I put myself in that position on purpose so I have that freedom.

What is something that you wish we could add in CSS?

I feel like every time someone asks this we all should take every opportunity to scream Container Queries! until we get them.

The idea is that we should be able to write CSS that says, "When this element is this wide, this CSS should take effect." And not just width, but whatever media queries we have at the page level already.

The best demo of a use case out there is Philip Walton's page.

I want to write a card component that shuffles itself around based on how wide it is, not how wide the page is, because there isn't always a direct connection between those two things (e.g. a card component can show up in a narrow sidebar on a large screen, but be full-width on a tablet or something).

Every component can be in a situation like that, so for the love of CSS, let me write media queries scoped to those components. I echo a lot of other people when I saw that if we had this, the vast majority of media queries we write would be these, not page-level.

Do you think it's worth suggesting a { position: above-fold; }?

I'm not sure I've ever made a big fold-based decision once in my career. Not a big fan of that thinking. THERE IS A LINE IN WHICH THIS IMPORTANT MODULE MUST NOT CROSS, haha. Prioritizing the most important stuff to be higher up the page, sure. Websites don't fold like newspapers.

Plus, we've got viewport units now, so if you absolutely need to position something in the top visible viewport area, you can.

Since you've been writing blog posts for so long, have you developed a process for writing one?

Sorta! It still feels pretty casual to me (let's call my writing medium quality), so it's not like I'm renting a cabin in the wilderness and finding inspiration in the sunsets and cheap whiskey.

  • I write down every blog post idea that comes to me. I try to keep that list fairly public but I also have a personal list where I can be even sloppier.
  • I put as much context into those lists as I can, so I can hope to summon up the same emotion that made me write it down in the first place. If I revisit the idea a week later and can't, it's probably not a very good idea.
  • I write up the post with as much context as I can. Light research is typically involved.
  • We have a lead editor on CSS-Tricks, so it's reviewed by at least one person before being scheduled.

CSS or CSS-in-JS?

I see a ton of cool stuff happening in CSS-in-JS. I think it solves a lot of interesting problems for certain websites. For example, I very much like the idea of having the option to write styles that are scoped to a component programmatically, and thus are tree-shaken when the component isn't used automatically.

But the web is a big place, and dare I say most websites aren't built with JavaScript-powered component models. Thus, CSS-in-JS isn't necessary or appropriate for a lot of sites.

Although, two things to be clear:

  • You can't have CSS-in-JS without CSS. CSS-in-JS is still styles that are applied to elements. It doesn't absolve you from learning CSS.
  • The CSS-in-JS landscape is wide. It's a little hard to talk about so vaguely. Each project in the bucket of CSS-in-JS handles things a bit differently and how the styles are applied to the site is even quite wide. I think it sometimes gets lost in the arguments that some of the approaches literally make a CSS stylesheet that you link up like you would any other CSS — even Sass-produced CSS — which there doesn't seem to be much argument about anymore.

The post Clips from my DEV AMA appeared first on CSS-Tricks.

Version 1 Prototype of the WordPress Admin Block Directory Announced

Mel Choyce-Dwan shared the first version of the WordPress admin block directory prototype the design team has been working on. The goal is to bring the block directory to the admin in WordPress 5.5, which is currently set for August 2020 on the roadmap. The post also outlines reusable components that can be used in other areas of the admin in the long term.

The Figma prototype is available for those who want to give it a test run. It is important to remember that this is an early version and many things can change by the time the block directory lands in WordPress.

The prototype was built after feedback from the first round of concepts shared in July on the Make Design blog.

For this admin project to be successful, WordPress plugin developers will need to start submitting blocks to the block directory on WordPress.org. At the moment, there are only 10 blocks listed. Getting in early will give block authors an edge on the competition. The block directory has a few additional guidelines beyond normal plugins that authors should review.

About Blocks Screen

Screenshot of the About Blocks screen prototype for WordPress.
About Blocks admin screen.

The About Blocks screen is the primary blocks admin screen. It appears to be an informational page with resources for users to learn more about using blocks on their sites. It also has links to development resources for designing and building blocks.

Making this information directly available, especially to users, would be a smart decision if it makes it into the final design. As we move toward an entirely new way to build websites with WordPress, it is important to provide learning tools to users. This seemed to be one of the missing components when the block editor first launched in core. If done right, it could ease the burden on new users and old users who are transitioning to the new editor.

The above screenshot also shows the new admin screen header proposal. The page title is followed by a short description of what the screen is about. Followed the intro are action links on the left and meta-type links on the right. I am a fan of the generous use of whitespace and extra information.

Add Blocks Screen

Screenshot of the Add Blocks screen prototype for WordPress.
Add Blocks screen.

The add blocks screen is similar to the current new plugin screen in the WordPress admin. The primary “Featured” tab (the tab opened when first visiting the screen) is broken down into various sections, such as “Blocks We Love” and “Popular Tags.”

One of the more interesting sections of this page is the “Top Authors” list. This concept would be a great way to give recognition to block authors who are building useful blocks for the community.

There is also a “Recent Blocks” section near the bottom of the page. I would rather see a top tab for that. It feels a bit buried in the current design. New plugin and theme authors already struggle to break into popular lists. Recently-added blocks should be higher up the page or have a dedicated tab/page to showcase them a bit more.

Installed Blocks Screen

Screenshot of the Installed Blocks screen prototype for WordPress.
Installed Blocks screen.

The block installation screen is similar to the existing installed plugins screen in core and lists all of the blocks that are installed. There are also active and inactive tabs. Improvements here are primarily around list table design. On the whole, they are minor adjustments, but the look of the tables is much nicer. Can we have this in core, across the board, now?

A new element is the “Instances” column, which lists the number of times a block has been used on the site. By clicking the number, you are taken to a new screen that lists the posts the block has been used in. It also displays the instances for each post. This would be a useful feature for deciding whether to deactivate or remove a block.

Side note to this: I have worked on numerous projects in the past where I was doing cleanup and attempting to figure out if a plugin, especially those with shortcodes, were in use on the site. Showing the instances count for blocks is brilliant.

Manage Blocks Screen

Screenshot of the Manage Blocks screen prototype for WordPress.
Manage Blocks screen.

Plugins such as EditorsKit have had built-in block management for a while. However, this feature feels like it should be in core WordPress. There are numerous core blocks that some users will likely never use. Having the ability to hide them from the block inserter will reduce clutter and make it easier to find the blocks they need.

The block management screen will allow users to activate or deactivate any specific block on their website. Like the block installation screen, it also displays the number of instances a block is in use.

Reusable Blocks Screen

Screenshot of the Reusable Blocks screen prototype for WordPress.
Reusable Blocks screen.

The reusable blocks screen is already available in WordPress. It does not currently have an admin menu link, so it is not easily discoverable. You can view it by going to the yoursite.com/wp-admin/edit.php?post_type=wp_block URL or clicking the “Manage All Reusable Blocks” link under the “Reusable” tab in the block inserter.

This screen allows users to manage blocks that are stored for reuse within multiple posts. Like the installation and management screens, the prototype displays an instances column for tracking how often the block has been used.

Users can import and export reusable blocks. It will be interesting to see if more WordPress users start sharing their block creations with others once this screen has better exposure or if it will be something people simply use to copy blocks from site to site.

Customize Your WooCommerce Website with Hooks

Among the top reasons to sell products or services online with WooCommerce is the WordPress plugin’s extensibility. Developers have extended it in all manner of ways. Everything from the look of your eCommerce shop to the types of products you sell can be changed and improved. And that’s just scratching the surface.

If you possess slightly more advanced development skills, there is a whole world of tweaks you can implement. They take place under the hood, so-to-speak, in your theme’s functions.php file or via custom plugins you can write yourself.

We’re talking about WordPress hooks. These are built in ways that you can interact with what a specific plugin, or WordPress itself, is doing. They’re highly useful for adding additional functionality or even changing the output of what’s displayed on the screen.

Luckily, WooCommerce has an extensive set of hooks available. You can use them to customize the shopping cart and tweak the user experience to match your needs.

Today, we’ll take a look at a few basic examples of how hooks can make WooCommerce that much better. But first, let’s explore why they’re often the best way to make customizations.

Why Use Hooks?

WordPress is nothing if not flexible. Thus, there are usually a number of different ways to accomplish the same thing. The same is true of WooCommerce.

For example, WooCommerce provides developers with the ability to override the various templates that the plugin utilizes. It might be a product page, a product category or even the checkout screen. If you need to add a custom bit of code, this is an easy enough way to do so.

However, the core versions of these templates are updated over time. If the particular template you’ve overridden is updated, you’ll need to reconcile that with any customizations. Otherwise, you run the risk of display errors or even the loss of functionality.

Hooks, on the other hand, don’t require you to directly edit a template. Instead, they allow you to insert code at a specific location and time. Since they are stored either in your theme’s functions.php file or a custom plugin, they remain largely unaffected by new versions of templates.

The sheer number of hooks built into WooCommerce often makes it a more effective and easier to maintain path to customization.

WooCommerce Hook Examples

Now that we know a bit more about why hooks are the preferred way to customize your cart, let’s take a look at a few examples of what they can do.

The following are basic code snippets that demonstrate the potential of hooks. They can add helpful information and functionality that improve the user experience. What’s more, these items can be added across the board or just in specific situations.

Add a Message to Product Pages

Imagine that you’re running an online store and you’re preparing for the holiday shopping season. You want to make sure that your customers know when the ordering deadline is for Christmas delivery.

While you could add a message to every individual product through the WordPress back end, that wouldn’t be very efficient. Instead, a hook could do the job in one shot.

Here’s the code, which goes into your theme’s functions.php file or a custom plugin:

What It Does
The hook, woocommerce_before_single_product, will place your code at the very top of each product’s page. Our custom function, my_product_notice_function, is the code that is added in and contains the special message.

Going Further
The above example would apply to ALL products within your shop. But what if you wanted to target only products within a specific category? There is a way accomplish that:

Now, we’ve managed to target just the products in the “Toys” category. Of course, there are a number of other possibilities here. You could, for example, display different messages based on a product’s category by adding in some conditional tags. Hooks really can be customized to match your exact needs.

A special message displayed on a WooCommerce product page.

Remove Related Products

By default, WooCommerce will show a listing of related products at the bottom of your product pages. But there may be times when you’d rather not show this information. A super-simple hook can take care of it.

Once again, the following code goes into your theme’s functions.php file or a custom plugin:

What It Does
As the name indicates, the remove_action() function is used to remove the function (woocommerce_output_related_products) attached to the specific hook (woocommerce_after_single_product_summary) we’re targeting.

Also note the number 20 in the code. This is the priority of our function and determines when it runs. The default priority is 10, so, the higher number indicates that it will run after the default. This ensures that the hook won’t be overridden by WooCommerce itself.

A listing of WooCommerce Related Products.

Rename a Product Tab

Hooks can also change the default output of WooCommerce. In this example from the WooCommerce Snippet Library, a filter will rename each of the three default tabs shown on product pages.

This code (you guessed it) should be placed into your theme’s functions.php file or a custom plugin:

What It Does
This function retrieves the title of each product tab (“Description”, “Reviews”, “Additional Information”) and changes their titles to “More Information”, “Ratings” and “Product Data”, respectively. You could, of course, change any of those titles to match your needs.

Renamed WooCommerce Product Tabs.

Creating a Better Shopping Experience

Just about every WooCommerce shop could benefit from some customizations. Each business is different and a default install simply can’t reflect all of the potential nuances.

Hooks are what can take a website from generic to a true reflection of a company’s brand and way of doing business. They allow us to add those little details that make for a unique user experience.

And, you don’t have to be a master developer to start using them. The examples above, basic as they are, can provide a great starting point. The best way to learn is often to take what’s already been done and experiment. Soon, you’ll find all sorts of situations where a hook can be just the thing your project needs.

How to Create a Spring Cloud Stream Binder From Scratch

Learn how to develop a custom Spring Cloud Stream binder from scratch.

Spring Cloud Stream is a framework built on top of Spring Boot and Spring Integration that is designed to build event-driven microservices communicating via one or more shared messaging systems.

The core Spring Cloud Stream component is called Binder,” a crucial abstraction that’s already been implemented for the most common messaging systems (e.g. Apache Kafka, Kafka Streams, Google PubSub, RabbitMQ, Azure EventHub, and Azure ServiceBus).

JVM Advent Calendar: How to Ally as Java Devs

Technology reflects the people who make it. Today, women make up 52 percent of the world population; however, most technology is designed by men. Women hold only approximately twenty percent of technology jobs and earn on average 28 percent less than what men make. Yet, it is proven that teams with both men and women are more profitable, smarter, faster, and more innovative — their collective IQ rises. As technology becomes more pervasive and we move to a more digital society, the impact grows beyond just those in the technology world.

In my role, as Director and Chairperson of the Java Community Process (JCP) Program, I also serve as an international speaker engaging the 12 million+ Java developer community worldwide — and in this space, as in the stats above, it is also primarily men. I love my job, and I love working with all kinds of people, but increasingly, community members ask me what we can do to change the ratio.

Redis-Based Bloom Filter for Java

Learn how to use Bloom filters in Java and Redis with the Redis Java client Redisson.

A Bloom filter is a probabilistic data structure that is used to efficiently test whether an element is present in a set. The use of Bloom filters can help reduce the number of expensive disk lookups for key-value pairs.

How Cloud Services Modernize ERP

Combining cloud and ERP

Today’s business environments are comparable to the old spinning plate trick on the Ed Sullivan Show from the 1960s. We all remember the famous scene: Erich Brenn running back and forth frantically keeping the plates spinning on each pole as the “Saber Dance” music plays in the background to enhance the drama. These plates in today’s parlance are the vast amounts of data that a business creates every day and keeping the entire engine running smoothly in terms of data analysis and security. ERP (Enterprise Resource Planning) tools and methods were devised in recent years to tackle the running of day-to-day operations in the office in terms of data, hardware, and software used by team members.

How to Choose The Right Automation Testing Tool

So many choices...


Test automation is gradually taking over manual testing as it saves time and improves the quality of testing. Especially in the case of regression testing, automation can improve efficiency by manifold. It is a waste of time and resources to do repetitive testing manually. Also, there is a scope for an error as repetitive testing can be exhausting but the chances of errors occurring in automation are slim. But what is automation testing? In simple terms,  automation testing is replacing manual human activity with a system that performs test cases by repeating predefined actions. To get the most out of automation it is necessary to select the right automation testing tool.

Top 10 Application Lifecycle Management Tools For The Year 2020

What Is Application Lifecycle Management?

Application Lifecycle Management (ALM) is used to manage and track the application development process. A plethora of ALM tools are available which help in handling all the aspects of a project like requirements management, customer support, IT service delivery, and quality assurance (QA), to name a few.To increase the efficiency of a project, it is crucial to find the right ALM tool.

Let us have a look at the ten most popular ALM tools for 2020.

Linux Find Command Tutorial (With Examples)

When it comes to locating files or directories on your system, the find command on Linux is unparalleled. It's simple to use, yet has a lot of different options that allow you to fine-tune your search for files.

Read on to see examples of how you can wield this command to find anything on your system. Every file is only a few keystrokes away once you know how to use the find command in Linux.

API Security Weekly: Issue #62

This week, we look at the recent API vulnerabilities in Amazon Ring’s Neighbors app and the Droom vehicle marketplace, articles on API security and WebSockets, an opinion piece on the most exploited API vulnerabilities, and a couple of recorded webinars.

Vulnerability: Amazon Ring

Gizmodo reports that Amazon Ring’s crime-alert app, Neighbors, exposes too much data through API calls. The coordinates included in the posted videos are so detailed that the locations of cameras and the users are exposed with extremely accurate precision.

How to Get the Current Page URL in Gatsby

This seemingly simple task had me scratching my head for a few hours while I was working on my website. As it turns out, getting the current page URL in Gatsby is not as straightforward as you may think, but also not so complicated to understand.

Let’s look at a few methods of making it happen. But first, you might be wondering why on earth we’d even want to do something like this.

Why you might need the current URL

So before we get into the how, let’s first answer the bigger question: Why would you want to get the URL of the current page? I can offer a few use cases.

Meta tags

The first obvious thing that you’d want the current URL for is meta tags in the document head:

<link rel="canonical" href={url} />
<meta property="og:url" content={url} />

Social Sharing

I’ve seen it on multiple websites where a link to the current page is displayed next to sharing buttons. Something like this (found on Creative Market)

Styling

This one is less obvious but I’ve used it a few times with styled-components. You can render different styles based on certain conditions. One of those conditions can be a page path (i.e. part of the URL after the name of the site). Here’s a quick example:

import React from 'react';
import styled from 'styled-components';

const Layout = ({ path, children }) => (
  <StyledLayout path={path}>
    {children}
  </StyledLayout>
);
    
const StyledLayout = styled.main`
  background-color: ${({ path }) => (path === '/' ? '#fff' : '#000')};
`;

export default Layout;

Here, I’ve created a styled Layout component that, based on the path, has a different background color.

This list of examples only illustrates the idea and is by no means comprehensive. I’m sure there are more cases where you might want to get the current page URL. So how do we get it?

Understand build time vs. runtime

Not so fast! Before we get to the actual methods and code snippets, I’d like to make one last stop and briefly explain a few core concepts of Gatsby.

The first thing that we need to understand is that Gatsby, among many other things, is a static site generator. That means it creates static files (that are usually HTML and JavaScript). There is no server and no database on the production website. All pieces of information (including the current page URL) must be pulled from other sources or generated during build time or runtime before inserting it into the markup.

That leads us to the second important concept we need to understand: Build time vs. runtime. I encourage you to read the official Gatsby documentation about it, but here’s my interpretation.

Runtime is when one of the static pages is opened in the browser. In that case, the page has access to all the wonderful browser APIs, including the Window API that, among many other things, contains the current page URL.

One thing that is easy to confuse, especially when starting out with Gatsby, is that running gatsby develop in the terminal in development mode spins up the browser for you. That means all references to the window object work and don’t trigger any errors.

Build time happens when you are done developing and tell Gatsby to generate final optimized assets using the gatsby build command. During build time, the browser doesn’t exist. This means you can’t use the window object.

Here comes the a-ha! moment. If builds are isolated from the browser, and there is no server or database where we can get the URL, how is Gatsby supposed to know what domain name is being used? That’s the thing — it can’t! You can get the slug or path of the page, but you simply can’t tell what the base URL is. You have to specify it.

This is a very basic concept, but if you are coming in fresh with years of WordPress experience, it can take some time for this info to sink in. You know that Gatsby is serverless and all but moments like this make you realize: There is no server.

Now that we have that sorted out, let’s jump to the actual methods for getting the URL of the current page.

Method 1: Use the href property of the window.location object

This first method is not specific to Gatsby and can be used in pretty much any JavaScript application in the browser. See, browser is the key word here.

Let’s say you are building one of those sharing components with an input field that must contain the URL of the current page. Here’s how you might do that:

import React from 'react';

const Foo = () => {
  const url = typeof window !== 'undefined' ? window.location.href : '';

  return (
    <input type="text" readOnly="readonly" value={url} />
  );
};

export default Foo;

If the window object exists, we get the href property of the location object that is a child of the window. If not, we give the url variable an empty string value.

If we do it without the check and write it like this:

const url = window.location.href;

...the build will fail with an error that looks something like this:

failed Building static HTML for pages - 2.431s
ERROR #95312 
"window" is not available during server-side rendering.

As I mentioned earlier, this happens because the browser doesn’t exist during the build time. That’s a huge disadvantage of this method. You can’t use it if you need the URL to be present on the static version of the page.

But there is a big advantage as well! You can access the window object from a component that is nested deep inside other components. In other words, you don’t have to drill the URL prop from parent components.

Method 2: Get the href property of location data from props

Every page and template component in Gatsby has a location prop that contains information about the current page. However, unlike window.location, this prop is present on all pages.

Quoting Gatsby docs:

The great thing is you can expect the location prop to be available to you on every page.

But there may be a catch here. If you are new to Gatsby, you’ll log that prop to the console, and notice that it looks pretty much identical to the window.location (but it’s not the same thing) and also contains the href attribute. How is this possible? Well, it is not. The href prop is only there during runtime.

The worst thing about this is that using location.href directly without first checking if it exists won’t trigger an error during build time.

All this means that we can rely on the location prop to be on every page, but can’t expect it to have the href property during build time. Be aware of that, and don’t use this method for critical cases where you need the URL to be in the markup on the static version of the page.

So let’s rewrite the previous example using this method:

import React from 'react';

const Page = ({ location }) => {
  const url = location.href ? location.href : '';

  return (
    <input type="text" readOnly="readonly" value={url} />
  );
};

export default Page;

This has to be a top-level page or template component. You can’t just import it anywhere and expect it work. location prop will be undefined.

As you can see, this method is pretty similar to the previous one. Use it for cases where the URL is needed only during runtime.

But what if you need to have a full URL in the markup of a static page? Let’s move on to the third method.

Method 3: Generate the current page URL with the pathname property from location data

As we discussed at the start of this post, if you need to include the full URL to the static pages, you have to specify the base URL for the website somewhere and somehow get it during build time. I’ll show you how to do that.

As an example, I’ll create a <link rel="canonical" href={url} /> tag in the header. It is important to have the full page URL in it before the page hits the browser. Otherwise, search engines and site scrapers will see the empty href attribute, which is unacceptable.

Here’s the plan:

  1. Add the siteURL property to siteMetadata in gatsby-config.js.
  2. Create a static query hook to retrieve siteMetadata in any component.
  3. Use that hook to get siteURL.
  4. Combine it with the path of the page and add it to the markup.

Let’s break each step down.

Add the siteURL property to siteMetadata in gatsby-config.js

Gatsby has a configuration file called gatsby-config.js that can be used to store global information about the site inside siteMetadata object. That works for us, so we’ll add siteURL to that object:

module.exports = {
  siteMetadata: {
    title: 'Dmitry Mayorov',
    description: 'Dmitry is a front-end developer who builds cool sites.',
    author: '@dmtrmrv',
    siteURL: 'https://dmtrmrv.com',
  }
};

Create a static query hook to retrieve siteMetadata in any component

Next, we need a way to use siteMetadata in our components. Luckily, Gatsby has a StaticQuery API that allows us to do just that. You can use the useStaticQuery hook directly inside your components, but I prefer to create a separate file for each static query I use on the website. This makes the code easier to read.

To do that, create a file called use-site-metadata.js inside a hooks folder inside the src folder of your site and copy and paste the following code to it.

import { useStaticQuery, graphql } from 'gatsby';

const useSiteMetadata = () => {
  const { site } = useStaticQuery(
  graphql`
    query {
    site {
      siteMetadata {
      title
      description
      author
      siteURL
      }
    }
    }
  `,
  );
  return site.siteMetadata;
};

export default useSiteMetadata;

Make sure to check that all properties — like title, description, author, and any other properties you have in the siteMetadata object — appear in the GraphQL query.

Use that hook to get siteURL

Here’s the fun part: We get the site URL and use it inside the component.

import React from 'react';
import Helmet from 'react-helmet';
import useSiteMetadata from '../hooks/use-site-metadata';

const Page = ({ location }) => {
  const { siteURL } = useSiteMetadata();
  return (
    <Helmet>
      <link rel="canonical" href={`${siteURL}${location.pathname}`} />
    </Helmet>
  );
};

export default Page;

Let’s break it down.

On Line 3, we import the useSiteMetadata hook we created into the component.

import useSiteMetadata from '../hooks/use-site-metadata';

Then, on Line 6, we destructure the data that comes from it, creating the siteURL variable. Now we have the site URL that is available for us during build and runtime. Sweet!

const { siteURL } = useSiteMetadata();

Combine the site URL with the path of the page and add it to the markup

Now, remember the location prop from the second method? The great thing about it is that it contains the pathname property during both build and runtime. See where it’s going? All we have to do is combine the two:

`${siteURL}${location.pathname}`

This is probably the most robust solution that will work in the browsers and during production builds. I personally use this method the most.

I’m using React Helmet in this example. If you haven’t heard of it, it’s a tool for rendering the head section in React applications. Darrell Hoffman wrote up a nice explanation of it here on CSS-Tricks.

Method 4: Generate the current page URL on the server side

What?! Did you just say server? Isn’t Gatsby a static site generator? Yes, I did say server. But it’s not a server in the traditional sense.

As we already know, Gatsby generates (i.e. server renders) static pages during build time. That’s where the name comes from. What’s great about that is that we can hook into that process using multiple APIs that Gatsby already provides.

The API that interests us the most is called onRenderBody. Most of the time, it is used to inject custom scripts and styles to the page. But what’s exciting about this (and other server-side APIs) is that it has a pathname parameter. This means we can generate the current page URL “on the server."

I wouldn’t personally use this method to add meta tags to the head section because the third method we looked at is more suitable for that. But for the sake of example, let me show you how you could add the canonical link to the site using onRenderBody.

To use any server-side API, you need to write the code in a file called gatsby-ssr.js that is located in the root folder of your site. To add the link to the head section, you would write something like this:

const React = require('react');
const config = require('./gatsby-config');

exports.onRenderBody = ({ pathname, setHeadComponents }) => {
  setHeadComponents([
    <link rel="canonical" href={`${config.siteMetadata.siteURL}${pathname}`} />,
  ]);
};

Let’s break this code bit by bit.

We require React on Line 1. It is necessary to make the JSX syntax work. Then, on Line 2, we pull data from the gatsby-config.js file into a config variable.

Next, we call the setHeadComponents method inside onRenderBody and pass it an array of components to add to the site header. In our case, it’s just one link tag. And for the href attribute of the link itself, we combine the siteURL and the pathname:

`${config.siteMetadata.siteURL}${pathname}`

Like I said earlier, this is probably not the go-to method for adding tags to the head section, but it is good to know that Gatsby has server-side APIs that make it possible to generate a URL for any given page during the server rendering stage.

If you want to learn more about server-side rendering with Gatsby, I encourage you to read their official documentation.

That’s it!

As you can see, getting the URL of the current page in Gatsby is not very complicated, especially once you understand the core concepts and know the tools that are available to use. If you know other methods, please let me know in the comments!

Resources

The post How to Get the Current Page URL in Gatsby appeared first on CSS-Tricks.

Raw GraphQL Querying

GraphQL has all kinds of awesome tooling built around it. But like everything on the web, it ultimately comes down to data shootin' across the ol' network and responses coming back. If you need to talk to a GraphQL API endpoint, you don't absolutely have to use some kind of framework or library to make requests against it. As a matter of fact, you can do it pretty cleanly in vanilla JavaScript.

Take the Pokémon API, available in GraphQL, which I found via this list of APIs. It has a GraphiQL interface for exploring.

From that page, you can execute queries and see the results. You can also poke into the Network tab in DevTools and see the payload for requests it sends off, and see that it's just a bit of JSON that is POSTed.

We can make our own JSON in that format too! First, we'll make it an object in the right format, utilizing template literals to make the GraphQL query look nice (which is actually required because the query syntax is dependent on white-space). Then we JSON-ify it with the native JavaScript API and POST it via the also-native fetch API.

See the Pen
Raw GraphQL
by Chris Coyier (@chriscoyier)
on CodePen.

Easy cheesy. And no fancy tooling to request exactly what you need, which is the core benefit of GraphQL.

The post Raw GraphQL Querying appeared first on CSS-Tricks.