Let's say that it's a WhatsApp-like, a decoupled, Drupal 8-backed, real-time chat platform that you're building. One using Node.js. In this case, implementing field autocomplete functionality becomes a must, doesn't it? But how do you add autocomplete to text fields in Drupal 8?
Needless to add that such otherwise "basic" functionality — implemented on fields like node reference and user/tags — would instantly:
improve the user experience
increase the level of user interactivity and engagement
Users would group around different "channels" and be able to easily add new members. The auto-complete text fields will make the whole “new member coopting” process conveniently easy:
Users would only need to start typing and an array of name suggestions (of the already existing team members) would spring up.
But let's see, specifically, what are the steps to take to implement autocomplete functionality in Drupal 8:
1. The Drupal Autocomplete Form Element: Adding Properties to the Text Field
The first basic step to take is to define your form element. The one that will enable your app's users, on the front-end, to select from the suggested team members' names. For this:
navigate to “Form” (you'll find it under “Entity”)
scroll the menu down to ”NewChannelForm.php”
Note: using “#autocomplete_route_name element”, when defining your form element, will let Drupal know that it should ignore it on the front-end.
And now, let's go ahead and assign specific properties to your form's text field! For this:
define “#autocomplete_route_name”, so that the autocomplete JavaScript library uses the route name of callback URL
define “#autocomplete_route_parameters”, so that an array of arguments gets passed to autocomplete handler
$form['name'] = array(
'#type' => 'textfield',
'#autocomplete_route_name' => 'my_module.autocomplete',
'#autocomplete_route_parameters' => array('field_name' => 'name', 'count' => 5),
);
And this is how you add #autocomplete callback to your fill-in form's text field in Drupal 8!
Note: in certain cases — where you have additional data or different response in JSON — the core-provided routes might just not be enough. Then, you'll need to write an autocomplete callback using the “my_module. autocomplete“ route and the proper arguments (“name” for the field name and “5” as count, let's say).
And here's specifically how you write a custom route:
2. Add Autocomplete to Text Fields in Drupal 8: Define a Custom Route
How? By simply adding the reference to the route — where data will get retrieved from — to your “my_module.routing.yml file”:
my_module.autocomplete: path: '/my-module-autocomplete/{field_name}/{count}' defaults: _controller: '\Drupal\my_module\Controller\AutocompleteController::handleAutocomplete' _format: json requirements: _access: 'TRUE'
Note: remember to use the same names in the curly braces (those that you inserted when you defined your “autocomplete_route_parameters”) when you pass parameters to the controller!
3. Add Controller with Custom Query Parameters
In the custom route that you will have defined, you'll have a custom controller AutocompleteController, with the handleAutocomplete method.
Well, it's precisely this method that makes sure that the proper data gets collected and properly formatted once served.
But let's delve deeper into details and see how precisely we can generate the specific JSON response for our text field element.
For this, we'll need to:
set up a AutoCompleteController class file under “my_module>src>Controller > AutocompleteController.php"
then, extend the ControllerBase class and set up our handle method (the one “responsible” for displaying the proper results)
it's the Request object and those arguments already defined in your routing.yml.file (“name” for the field name and “5” for the count, remember?) that will pass for your handler's parameters
the Request object will be the one returning the typed string from URL, whereas the “field_name” and the “count” route parameters will be the ones providing the results array.
Note: once you get to this step here, as you add autocomplete to text fields in Drupal 8, remember that you should be having data in “value” and “label” key-value, as well:
Next, you'll set up a new JsonResponse object and pass $results, thus generating a return JsonResponse.
Summing Up
That's pretty much all the “hocus pocus” that you need to do to add autocomplete to text fields in Drupal 8. Now the proper data results should be generated.
Just reload your app's form page and run a quick test:
Try to create a brand new channel in your app and to add some of the already existing team members.
Does the text field have autocomplete functionality added to?
RADU SIMILEANU / Jul 18'2018
All sorts of highly likely confusions, data taken out of its context, “obsessing over” numbers, approaching analytics with no clear goals in mind, metrics subjected to your own biases... We're all prone to making mistakes when analyzing data. Still, as a UX team striving to pull off an accurate picture of the user behavior, you need to take note of the most common mistakes in interpreting analytics data (UX analytics).
… of the biggest "gaffes" in reading data.
Those responsible for all the wrong assumptions about your users that you'll end up making:
that low numbers are always a bad sign
that if results show a correlation, there is definitely a causal relationship, as well
... and so on.
Now, allow me to “expose” to you the 7 most common mistakes that one can make when interpreting statistics:
1. Visits and Views: Confusing Them and Obsessing Over Them
Using these two notions interchangeably is a pitfall that not only rookie data analysts fall into:
With different UX analytics tools using different terminology for the very same concept and (even) confusing terminology used within the same tool, no wonder that you end up taking views for visits and vice versa.
And still: make sure you fully understand the terminology, otherwise you risk to:
report on the wrong data
put together some dangerously inaccurate reports
This is, no wonder, one of the most common data interpretation errors.
Now, let's define views and visits and present them as two different concepts once and for all:
a view (or “pageview”) refers to a view of a page on your website tracked by the analytics tracking code
a visit (or “session”) refers to a user's whole of interactions taken on your site, within a specific time frame
And now, speaking of views and visits, another one of the too common mistakes in interpreting analytics data is:
Obsessing over views and visits!
As a UX designer though, you may want to leave the challenge of increasing visits and page views to the marketing people in your team to handle. And, instead, to focus your efforts on that data that 's relevant to the user experience.
2. Settling for a Birdseye View Instead of Digging Deeper into Data
Scratching the surface of the available data:
a quick assessment of the data at hand
rapidly going over the “headline” figures
… will only tell you something about your website's current performance in terms of traffic, but won't give you any clue on how to improve UX. How to increase the conversion rate.
In other words: visits are no more than metrics signaling you how many visitors landed on your site during a given period of time, but this metrics won't reveal anything about how they actually engaged with those visited pages.
See? Analyzing data as broadly as considering sessions to be the key indicator of performance and UX is another one of those common pitfalls in interpreting statistics:
By far the best method of reading analytics data, as a UX-er, is to approach it with some well-defined goals in mind. This way, you'd focus your efforts on specific metrics, relevant for understanding user behavior, instead of getting yourself “drown” in a sea of data.
3. Common Mistakes in Interpreting Analytics Data: Not Looking Beyond Numbers
… and not putting them in their contexts.
For that's the proper way to interpret them. Otherwise, you're just... analyzing quantitative data stating the obvious:
The “what” and not the “why”.
This is undoubtedly one of the most common mistakes in interpreting analytics data: falling under the “spell” of numbers!
Instead, you'll need to keep in mind that:
it's real users that those collected numbers represent
once taken out of their contexts, numbers lack their true value
they become truly valuable only when interpreted in connection with the user experience:
What do they tell you about the overall user experience on your website?
This is why you should always apply qualitative methods when analyzing quantitative data. User research methods that enable you to go from “what has happened” to:
“Why is it that visitors behaved that way on my website?”
4. Always Taking Low Numbers for a Bad Sign
Another one of those more than common mistakes in data analysis is:
Always thinking that low or a drop in numbers is a bad thing.
Context is everything here!
Just think of reading data analytics as a three-phase process:
what you want to see in those numbers
what the available data seems like
what it really means
Let me give you one good example:
Less time spent on a web page could be good or bad. If we're talking about your redesigned homepage, it could very well mean that users do find its new design more intuitively efficient. That they can get to the pages on your site that they're interested in far more easily.
In other words: do put those drops in numbers against their contexts before you alert everyone in your team that the site's going down the hill!
5. Overlooking to Segment Users
For you surely agree that every given visitor uses your website differently:
on desktop
on mobile
at different times of the day
And that multiple users interact differently with your site.
Need I say more?
Don't overlook these valuable considerations on your users' behavior when interpreting your quantitative data.
Before you rush to make all the wrong assumptions reading your analytics data, make sure you break those figures down into multiple relevant segments:
mobile users
desktop users
users from different countries
users falling into different age groups and so on
It's user base segmentation that turn quantitative data into... relevant data. And which, most importantly:
Provide you with priceless clues regarding the areas on your site that you should be focusing your UX efforts on.
Let's just say that your site has a conversion rate of 7%. Before you get overexcited about it, make sure you break that figure down. You might just discover that 9% comes from your desktop users and only 1% from your mobile users.
And there you have it, there's your clue! Now you know just where to focus your UX efforts.
6. Not Setting Clear Goals Before Approaching Your Analytics
And, as already stated, this could get you “tangled up” in a huge amount of data.
But, if you take some time to define your goals first things first, you'll know just what you'll want to achieve from your data analysis session.
And to:
direct your UX efforts towards those specific objectives
focus exclusively on those metrics relevant for interpreting user behavior
If you don't know where you're heading, how can you know just how to get there; how to improve UX on your website?
7. Settling for a One-Size-Fits-All Reporting Setup
Another one of those common mistakes in interpreting analytics data is sticking to a standard reporting setup.
That instead of trying to custom-tune it so that it should deliver you precisely the data you need. The one relevant for your own website.
Since each site works differently, you can't expect a one-size-fits-all approach to data analytics to perfectly suit them all, in the slightest details, now can you?
So, You've Analyzed Your Data: Now What?
For reading your analytics data is just the first step. Now it's time you:
get some actionable takeaways from your analyzed data
get to action
Are there usability tests that you need to run to figure out why the conversion rate is higher on your desktop site than on its mobile version?
Or maybe you need to implement some user research methods to identify those contexts where users visit your site from their mobile devices?
Time to put together your “data-fueled battle plan”!
Adriana Cacoveanu / Jul 12'2018
I'm a woman of my word, as you can see: here I am now, as promised in my previous post on the most effective ways to secure a Drupal website, ready to run a “magnifying glass” over the best Drupal security modules. To pinpoint their main characteristics and most powerful features and thus to reveal why they've made it to this list.
And why you should put them at the top of your own Drupal security checklist.
So, shall we dig in?
1. Login Security
It's only but predictable that since the login page/form is the entry to your Drupal site, it is also the most vulnerable page there, as well.
Therefore, secure it!
In this respect, what this module enables site admins to do is :
define a certain number of login attempts; too many invalid authentication attempts will automatically block that account
block/limit access for specific IPs
Moreover, you get notified by email or via Nagios notifications when someone is just username/password guessing or using other kinds of brute force techniques to log into your Drupal site.
In short: the Login Security module, through its variety of options that it “spoils” you with, empowers you to set up a custom login policy on your site. To define your own restrictions and exceptions.
2. Drupal Core Update Module
As already mentioned here, on this blog, when we've tackled the topic of Drupal security:
Keeping your Drupal core updated is that easily underrated, yet most powerful security measure that you could implement!
Now what this module here does is assisting you in keeping your Drupal codebase up to date: safely patched and having all the crucial upgrades.
And I don't need to remind you the security risk(s) that all those site owners ignoring the latest patches to Drupal core expose their websites to, right?
3. Captcha
Captcha is one of the best Drupal security modules since it's one of the most used ones.
And no wonder: could you imagine submission forms on your website with no Captcha? The age-old system is one of the handiest ways to keep spammers and spambots away.
So, having this module “plugged in”, providing you with the needed captcha support, becomes wisely convenient.
4. Password Policy
The module enables you, as your Drupal site's admin, to define specific rules for “wannabe users” to follow when they set up their account passwords.
From constraints related to:
special symbols that those passwords should include, to ramp up both the given account's and your own site's security
to uppercase letters
to numbers...
… once you plug in this Drupal security module in, it's you who gets to set up the policy for creating account passwords.
5. Security Review, One of the Best Drupal Security Modules
The Security Review module is that “Swiss knife” that you need for hardening your site's shield.
Meaning that it's an all-in-one tool. One that comes with its own Drupal security checklist that it regularly goes through and sets against your website, detecting any missing or improperly implemented security measures.
Moreover, it automates a whole series of tests for tracking down any signs of exploits and brute-force attacks:
arbitrary PHP execution
XSS exploits
SQL injection
suspicious PHP or JavaScript activity in content nodes
Once it identifies the vulnerabilities, it “alerts” you and gives you the best recommendations for mitigating those security risks. All you need to do is follow the suggestions.
6. Security Kit
Another module that “empowers” you to take full control over the security strategy on your Drupal site. To set up specific options for minimizing the chances of exploitable “cracks” showing up in its security shield:
For instance, it could recommend you to set up HTTP headers on your Drupal site.
7. Session Limit
Here's another one of those best Drupal security modules that's also one of the widely used ones.
Why is it a must-have on your own Drupal site? Because it enables you to set a limit to the number of simultaneous sessions per user, per role.
This way, you trim down the chances of suspicious activity being carried out on your site and eventually leading to brute-force attacks.
8. Automated Logout
Another module that's a must on your Drupal site:
It basically enables you, the site admin, to define a policy that would log out users after a specified time period of inactivity.
9. Two Factor Authentication
LinkedIn, Google, Twitter, Instagram, Facebook are just some of the big names that have adopted this user authentication method for security reasons. So, why shouldn't you, too?
Especially when you have a dedicated module at hand, Two Factor Authentication, to:
provide you with various methods to select from: pre-generated codes, time-based one-time PINS or passwords, codes sent via SMS etc.
give you full freedom in defining that two-factor authentication strategy that suits your site best
The principle is as simple for the user, as it is effective for your website, from a security standpoint:
The user gets a security code that he/she'll then need to use for logging into your Drupal site.
10. Coder
A command-line tool, with IDE support, that gives your codebase a deep scan and detects any drift from the coding standards and best practices.
Why has it made it to this exclusive list of 15 best Drupal security modules? Cause vulnerabilities might be lurking right in your Drupal code, not necessarily in your users' weak passwords or unpatched core modules.
Having a tool at hand that would identify and notify you of all those weak links in your code, where the best practices aren't being followed, is just... convenience at its best.
11. SpamSpan
Another key module to add to your Drupal security checklist.
For you do agree that email addresses are some of hackers' easiest ways to infiltrate into your website, don't you?
Now what this module here does is obfuscate email addresses so that spambots can't collect them.
Note: a key strength of SpamSpan is that it uses JavaScript for this process, which enhances accessibility.
12. ACL
“A set of APIs” This is how we could define this module here, which doesn't come with its own UI.
Its key role? To enable other Drupal modules on your website to set up a list of users that would get selective access to specific nodes on your site.
13. Paranoia
Why is Paranoia one of the best Drupal security modules?
Because it will end your “paranoia” — as its name suggests — that an ill-intentioned user might evaluate arbitrary code on your site.
The module practically identifies all those vulnerable areas where a potential attacker could exploit your site's code and blocks them.
14. Content Access
Limiting or blocking access to key content types on your site is no more than a common-sense security measure to take, don't you agree?
Therefore, this module here's designed to assist you throughout this process:
as you define detailed permissions on your site: to view/edit/ delete specific content types
… by user role and by author
Word of caution: do keep in mind that, since Content Access uses Drupal's node API, you shouldn't enable other modules using the same endpoints on your website!
15. Google Apps Authentication
A module that ramps up not just your site's security, but also its accessibility.
Just think about it:
Nowadays anyone has at least one Google account. Therefore, “anyone” can easily log into your website using his/her own Google account credentials.
Once, of course, you will have installed and turned this Drupal module on.
END of the list! These are the 15 best Drupal security modules worth installing on your site.
Scan them through, weigh their key features, set them against your site's specific security needs, and make your selection!
If you want to access expert Drupal support for your development projects, contact Optasy.
Adriana Cacoveanu / Jul 04'2018
You have patched your Drupal website, haven't you? If so, then that critical 3-month-old security flaw, Drupalgeddon2, can't get exploited on your site. Even so, with the menace of a cryptocurrency mining attack still lurking around the unpatched websites, you legitimately ask yourself: what are some quick and easy ways to secure Drupal?
“Which are the most basic steps to take and the simplest best practices to adopt to harden my Drupal site's security myself?”
Now, using keywords such as “security measures”, “quick”, “easy” and “handy”, I've come up with a list of 7 basic steps that any Drupal site owner can (and should) take for locking down his/her website.
Here they are, in no particular order:
1. Keep Your Drupal Core and Modules Updated
Not only is this one of the simplest ways to secure Drupal, but one of the most effective ones, as well.
Even so more now, with the Drupalgeddon2 Drupal security threat still fresh in our memory, ignoring the regularly released security updates for both Drupal core and its modules is just plain recklessness or... self-sabotage.
Keep your Drupal version updated: apply security patches as soon as they get released, avoiding to leave your site exposed and exploitable. As simple as that!
And where do you add that this is one of those Drupal security best practices that's the easiest to integrate into your routine. Since to run the latest updates you only need to:
sign in to your Admin panel
go to “Manage”
scroll down to “Reports” → “Available Reports”
click on “Check manually”
if there are any critical security updates that you're advised to run, just click “Update”
This is all it takes for you to:
seal any security loopholes in your Drupal core
prevent any identified vulnerability from growing into a conveniently easy to access backdoor for hackers to get in
2. Install Drupal Security Modules
Strengthening the shield around your Drupal site with some powerful Drupal security modules is another both handy and effective measure that you, yourself, can easily implement.
Luckily, you're definitely not out of options when it comes to good security modules in Drupal.
And I'm only going to run a short module inventory here, since I'm already preparing a blog post focused precisely on this topic. Therefore, I promise to delve deep into details about each one of the here-listed modules in my next post:
Secure Login
The Security Review (Drupal 7 only)
Paranoia
Captcha
Two-factor Authentication
Content Access
Security Kit
Password Policy
Automated Logout
Password Strength
Downloading, installing security modules on your Drupal site is both:
quick and simple to do
highly effective
And they serve a wide range of purposes, from:
enforcing strong password policies
to monitoring DNS changes
to locking down your site from security threats
to blocking malicious networks
to turning on a firewall on your site
As for their selection, it depends greatly on your list of priorities when it comes to improving your site's security. Take some time to weigh and to compare their features.
3. Remove Unused Modules: One of the Easiest Ways to Secure Drupal
Being the “easiest” security measure to implement doesn't make it also “the most popular” among Drupal site owners.
Owners who more often than not:
underrate the importance of running a regular module usage audit on their sites
ignore the Drupal security threat that an outdated piece of code (or an unused module) could turn itself into, once exploited by an attacker
So, don't be one of those site owners! Are there modules on your site that you no longer use?
That have grown outdated and that are just... lingering there, using your site's resources and risking to grow into an exploitable backdoor for hackers?
Identify them and remove them! It won't take more than just a few priceless minutes of your time.
4. Enforce a Strong Password Policy
Since it's not just the admin (you do have a smart username and password for logging into your admin dashboard, don't you?) that will log into your Drupal site, but users, too, implementing some strong user-side security measures is a must.
In this respect, creating a strong password policy — one that would enforce the creation of complex, “hard-nut-to-crack” type of login credentials — is one the best and the easiest ways to secure Drupal on the user's side.
Come up with a policy that defines specific requirements for setting up passwords of high enough entropy (letters, uppercase/lowercase, symbols, different characters combos).
And don't hesitate to rely on dedicated Drupal modules for enforcing those requirements defined in your policy:
Password Strength
Secure Login
5. Block Access to All Your Sensitive Files
I bet you don't want important folders, core files — upgrade.php., install.php, authorize.php, cron.php — to be easily accessible to just... anyone, right?
So, how about limiting or blocking access to them?
And you can easily do that by configuring your .htaccess file — it's the one containing details of crucial importance regarding your website access and credentials to specific parts and core files on your site:
Just specify the IP addresses allowed to access those core folders, files and subdomains.
Here's one “enlightening” example:
<FilesMatch "(authorize|cron|install|upgrade)\.php">
Order deny, allow
deny from all
Allow from 127.0.0.1
</FilesMatch>
Note!
Now speaking of limiting access, don't limit your restrictions to your core folders and files. Remember to restrict/block access to your web server, to your server login details, as well.
How? By adding a basic layer of authentication limiting server access and file access usage.
Also, do remember to cautiously manage access to certain port numbers that your site/app might be using.
6. Back Up, Back Up, then... Back Up Some More
You can't anticipate brute-force attacks, but you sure can “land back on your feet” if the worst scenario ever happens.
And you can only do that if you have a clean and recent backup at hand to just rollback and restore your website.
In other words: back up regularly!
And remember to always back up your files and MySQL database before any update that you run on your Drupal code and modules. It is one of those common sense Drupal security best practices that should be included in any basic security checklist!
Where do you add that you even have a dedicated Drupal module — Backup and Migrate — to assist you with this process.
Some of the back up “burdens” that this module will take off your shoulders are:
backing up/restoring code and multiple MySQL databases
integrating Drush
backing up files directory
setting up several backup schedules
AES encryption for backups
7. Review All User Roles and Grant the Minimum Permissions Necessary
How many user roles are there assigned on your Drupal site?
If you don't quite know the answer, then it's obvious:
You must give your entire user role system an audit!
And to stick to this habit, one of the simplest ways to secure Drupal, after all.
Review all the user roles and, most of all, review each one's set of permissions and make sure you trim them down to the minimum necessary for each role.
This way, you'll also limit access to critical files for those users that shouldn't have the permission to download or visualize them.
And speaking of permission, do keep in mind to review all your file permissions, as well!
See which user roles are granted permission to access key directories or to read, write or modify certain files on your website and block/restrict access where necessary.
The END! Of course, this isn't even close to a complete list of ways to secure Drupal. If it had been an exhaustive one, it would have continued with more Drupal security best practices, such as:
getting the SSL Certificate
securing HTTP headers
using secure connections only
Etc. etc. I've only focused on some of the easiest and quickest measures that anyone, with little, close to no technical know-how at all, can implement. And I feel like stressing out the term “practice” here:
Securing your Drupal site is a constant process; a series of persistent efforts and not a one time thing. Remain vigillant and cautious and don't rely on just a one-time, multifaceted security hardening “marathon”.
Adriana Cacoveanu / Jun 28'2018
Oops! The worst has happened: your Drupal site has been hacked! Maybe it was precisely one of those critical vulnerabilities, that the Drupal security team has been drawing attention to these last months, that the attacker(s) exploited?
Now what? What to do?
Should you be:
rushing to restore your website to a healthy, good-working state (that, of course, if you do have a clean and recent backup available)?
starting to rebuild it?
investigating how your Drupal site got contaminated in the first place: where's the “open door” that the attackers used to get in?
focusing on closing any backdoors that could make new attacks possible?
Now “tormenting” yourself with too many questions simultaneously will only distract you from what should be your main objective: cleaning up your website (and preventing further hacks I should add).
So, let's go about it methodically, step by step:
Step 1: Write Down Issues, Steps to Take, Preventive Measures to Apply
Keep your cool and go for a methodical approach to crisis management:
Just open up a document and start... documenting:
the issues and any suspicious activity that you identify on your site
all the steps that your strategy for removing malware and restoring your site should include
the preventive security measures you commit to taking for preventing such a scenario from happening again the future
Step 2: Make a Forensic Copy of Your Drupal Site
Before you start running your “investigations” on the attack, on how your Drupal site has been hacked, and way before you get to rebuild anything:
Make a forensic copy of all your files, you database and your operating system environment!
Note: go with an external storage medium for these copies and store them offsite.
As you're scanning through your files, detecting viruses and malware and having them cleaned up, feel free to make new and new “working backups”. And to store them in a different directory (from your regular backup files, I mean).
“But why bother? When will these backups turn out particularly useful?”
when you call out to a third party to assist you with the troubleshooting process; these “working” backups will then provide a clear picture of the site before you started “malware detecting” on your own
when you try to fix the issues you detect, but instead you make them worse; then, you can easily roll back those changes
Step 3: Scan Your Servers and PC for Malware, Malicious Code Injections, Viruses
Before you rush to change all the passwords on your site, pause for a moment to think through your next “move”:
What if the attack has been “programmed” so that the attacker should get notified once you change your password(s)? And what if it's precisely your PC or one of your servers that's got infected? Then storing a clean backup of your site precisely there would only make it even more vulnerable.
So, how do you prevent that? You give both your PC and your servers a deep scan before making any change.
And, thank God, you sure aren't nickel and dimed in anti-malware tools and anti-virus software: AVG, BitDefender, Malwarebytes, ESET, AV-Comparatives etc.
Step 4: Detect & Remove the Backdoors
One of the crucial steps to take, once you realize that your Drupal site has been hacked, is to “close” all the backdoors.
These could easily turn into hackers' access ticket into your site even after you've removed malware and restored it to its healthy state. But, for closing them you first need to... find them right?
So, where to look?
Here are a few key places on your site that you should focus your “searches” on:
access logs: while scanning them, be vigilant and look for PHP scrips and POST requests added to directories that have writable access
eCommerce set up: check all the payment methods, shipping addresses, credit card addresses, linked accounts, looking for any suspicious, newly added data
passwords: FTP passwords, admin passwords, control panel passwords
email rules and filters: check that the answers to the security questions are “legitimate”, that messages are being forwarded to correct email addresses etc.
Step 5: Consider Taking Your Site Offline
And your decision depends greatly on the nature of your site:
If it's a hacked eCommerce Drupal site that we're talking about here, then don't wait even one more minute: take your site down (along with the internal network and servers) and install a placeholder!
This way, you'll prevent:
malware from being further distributed
spam from being sent to your online store's customers
Note: do keep in mind that taking your site offline will instantly let the attackers know that you've detected the malware that they've “infiltrated” and that you are about to “take action”.
If you decide not to take your Drupal site offline at the web server level, ensure that you've got your clean forensic copy at hand before deleting all the sessions.
Note: have you detected suspicious changes of the passwords? If so, use this query here for updating them (Drupal 7):
update users set pass = concat('ZZZ', sha(concat(pass, md5(rand()))))
As for the users, they can easily use the reset password tool for updating their passwords.
Word of caution: mind you don't take "Drupal on maintenance mode” for “offline Drupal". They're 2 completely different things! Once your Drupal site has been hacked, the malware could be of such nature that it allows the attacker to infiltrate as long as the site's online.
Step 6: Notify Your Hosting Provider That Your Drupal Site Has Been Hacked
They should be informed about the breach and about your site being taken offline (if it's the case) immediately.
The sooner the better, this way they can:
start scanning their own systems for incursions
get ready to assist you with your site recovery and securing process
Step 7: Handle Client Data with Extra Precaution
And these are the specific scenarios where you'll need to take extra precautions when handling client information:
your Drupal site stores client information on the web host
… it leverages the data POST method for sending form data via e-mail
… it doesn't integrate with a 3rd party payment gateway, but manages the payment processes itself
If one of these 3 scenarios suits your case, then here are some of these extra precautions that you need to make to ensure the private user data doesn't get exposed:
update your SSL certificate
re-check all logfiles (have any of the hosted client information been copied, updated or downloaded?)
implement AVS (address verification system)
add CVV (card verification value)
encrypt connections to back-end services used for sending confidential user data
Step 8: Investigate the Attack: Identify the Source(s) of Infection
No matter how much pressure you might find yourself under to get your site back online ASAP, don't let take control over your site's restoring process!
Not until you've detected the main source of contamination on your site. The key vulnerability that attackers exploited, the key reason why your Drupal site has been hacked in the first place.
That being said, make sure that:
you first audit, on a staging server, that “clean” backup of your site that you're planning to get online; this way, you track down and remove infected files, unauthorized settings, malicious code
you compare pre- and post-hack files, looking for any suspicious changes
Now if you have a clean (and recent) backup at hand for running this comparison, the problem's almost solved. Just use the right tools to compare your files and track down discrepancies.
But if you don't have a backup at hand, then there's no other way but to:
Manually inspect your files and databases to identify any suspicious changes that have been made.
look for any suspicious iframe or JavaScript at the end of the files (if detected, save the code in an external file)
look for any sources of “Drupal site hacked redirect”; for links to external URLs
Now, as for the places that you should be running your investigations on, let me give you just a few clues:
.php files, .html files
sessions table
newly modified/created files
new/updated user accounts
in writable directories and database
Step 9: Do a Full Restore of Your Site
So, you've noticed that your Drupal site has been hacked, you've assessed all the damage caused, removed malware and even detected the vulnerability that hackers exploited to get in, not it's only but logical to:
Try to repair your website, right?
Word of caution: never ever run your changes on your production site; instead, fix all detected issues on a staging site. Also, once you've cleaned it all up, remember to run the latest Drupal security updates, as well!
Now, getting back to repairing your site, you have 2 options at hand:
you either restore a clean backup, if you know the date and time that your Drupal site has been hacked and you're also 100% sure that none of the system components, other than Drupal, got contaminated
or you rebuild your Drupal site
The latter method is, undoubtedly more cumbersome, yet a lot more cautious. Go for it if:
you do not know the precise date and time when your site's got contaminated
you do not have a clean (and recent) backup available to restore
you've evaluated the damages as being already too widespread
Step 10: Give Your Restored Site a Full Check Before Going Live
Do remember to give your newly recovered site a final audit before getting it back up:
remove all malicious code detected
suspicious files
unauthorized settings
And, most of all:
Close all the backdoors!
Final Word
A pretty long, complex and discouragingly tedious recovery process, don't you think?
So, why wouldn't you avoid all these steps that you need to go through once your Drupal site has been hacked?
Why not avoid the risk of finding yourself forced to take your website offsite for... God knows how long, risking to impact your site's reputation and to drive away users/online customers?
Don't you find it wiser to:
be prepared instead?
opt for ongoing Drupal maintenance and support services?
make a habit of regularly backing up your website?
keep your system and software up to date (and to install all the recommended patches)?
stop underrating the security advisories that the Drupal team makes?
RADU SIMILEANU / Jun 25'2018
If only there was a... button that you could just press to convert your app to Android or iOS, right? Or if only a quick and easy recompilation process had been enough. Or if the “Let's just make it look similar” approach was your “winning card”... There is no such thing as “easier way” to port an Android app to iOS and vice versa.
Instead, there are essential aspects to consider and to adjust your whole app porting process to, meant to stir you in the right direction:
navigation
design considerations/UX
screen size and resolution
code and essential app architecture differences
3rd party services, frameworks, extensions, and used libraries
And, as you might just guess, the list is incomplete. For it includes other factors, as well, such as device support, customer and business model considerations and so on...
To keep your app's architecture intact, while porting your app between Android and iOS — 2 platforms with drastically different UIs and core structures — considering the above-mentioned 5 factors becomes crucial.
Therefore, let's detail them, shall we?
But What Does App Porting Actually Mean? Its 4 Key Stages
Let's start with some sort of definition of the whole process:
By porting your mobile app you're changing or rewriting its code so that it should work on a different mobile OS than the one that it's been initially developed for.
Clear enough?
“How long does it take to port an Android app to iOS and vice versa?” you might ask yourself.
Usually from 1 to 6 months, but it depends greatly:
on your app's complexity
on its core architecture
on the entire ecosystem of libraries that it uses, on its design particularities
on the business logic behind
Speaking of which, analyzing precisely the driving business logic is as critical as it is underrated by developers who usually stick to: adapting a platform and eventually writing the needed extra code.
“And what are the essential steps to take to porting my app?”
Glad you asked. Here are the main stages that an effective mobile app porting process should include:
analysis and plan
technical assessment
the porting itself
intensive QA
1st Factor to Consider When You Port an Android App to iOS: Navigation
Navigation is the factor that "miles" sets apart the user behavior on Android phone from the user behavior on iPhones.
Here's why:
Android devices are equipped with 3 different buttons: Home, Back and Multitasking button
iPhones only have the home button
Now, imagine tapping a multitasking button as in the Android platform: you can't get away with a simple transfer to iOS. Instead, you'll need to write the proper code for it from scratch.
And there's more to navigation and to the way that it is drastically different from one platform to the other. For instance:
Both horizontally and vertically displayed elements on iOS vs vertical elements only, on Android devices.
Tip: if you wish your iOS app to look similar to its Android alternative, there's always the handy compromise that you can make of placing in-app tabs in the bottom of the screen.
2nd Factor to Consider: Design Considerations/UX
You'll have to reconstruct your app's user interface from scratch to convert it from Android to iOS (or the other way around)!
Face it, deal with it and... adapt your “battle plan” to it!
There's no way around this:
When it comes to UI, Android and iOS are just... worlds apart! Android taps into material design, contrasting Apple's signature flat design.
Now here are the key design elements that you should pay special attention to, along with some tips on how to make their porting... smoother:
icons: each platform provides you with its rich icon library
dialogs
font styles: San Francisco or Helvetica Neue in iOS and Roboto in Android
content navigation
lists
object placement: flat vs hierarchical object placement
text alignment: center aligned test in iOS vs left alignment of the text in Android
buttons: iOS “favors” flat buttons with shadows, whereas in Android you'll find both flat and floating action buttons
Word of caution: when porting apps to Android or from Android, keep in mind the pixels vs points (pt) difference when it comes to measuring icons and font sizes in the two platforms
3rd Factor to Consider: Screen Size and Resolution
Briefly put: it will be conveniently smoother to port an Android app to iOS than vice versa.
Why? Because in Android you have a varied collection of screen sizes and resolutions at hand, whereas in iOS it's significantly lighter.
So, if it's an app porting to Android that you're planning, do take into consideration all those screen resolutions that are missing in iOS.
4th Factor to Consider: Your App's Essential Architecture
And here's the right approach to adopt when you port an Android app to iOS (or vice versa) and you're preparing to build its new architecture:
Identify the minimum OS version that your ported mobile app should support and set up its architecture accordingly.
5th Factor(s) to Consider: Frameworks, Libraries, Extensions, Code
Your current app's “infrastructure” of libraries, extensions, 3rd party services and frameworks play a critical role.
A “too critical role” not to turn it into an essential factor to consider once you decide to port your app to a new OS.
Therefore, for each one of the used libraries that's not compatible for cross-platform usage you'll need to find a suitable equivalent. And it goes without saying that this calls for:
A proper testing of each given framework and 3rd party library, to know for sure which ones support both OS and which ones don't.
The good news is that most of them do support them both, making it smoother for you to duplicate most of your app's basic functionalities when converting it to another OS.
Now when it comes to the aspect of code, the fact that the 2 platforms use different programming languages influences greatly the way you should port an Android app to iOS:
Kotlin and Java are used for building Android apps, whereas Swift is used to develop iPhone apps. Therefore, you can't get away with simply compiling your app's current code into its new ported version.
Note: I know what you might be thinking, that both OS support the C-code instead and so, that you could transfer your codebase to the other platform. Yet, it has already been proven that porting apps to Android from iOS calls for a complete rewriting in a different language.
How long would it take you? It depends greatly on your app's feature set, on the used 3rd party libraries, complexity etc.
Final Word
As you can see, once you decide to create a “clone” of your iOs app for the Android platform or vice versa, you'll need to take “recompilation” out of your mind.
Porting your app won't be that simple!
With the 2 platforms having completely different user interfaces and core structures:
careful planning and in-depth analysis (and yes, I'm thinking business logic here) becomes crucial
taking into account all those elements that set these OS worlds apart (interface, navigation...) and adjusting your porting strategy accordingly is the only effective way to port an Android app to iOS or vice versa
Adrian Ababei / Jun 21'2018
“Mysterious” pop-ups that you did not initiate, inexplicable auto-linking keywords, frequent freezing of your website... These are all but clear signs that your WordPress site has been hacked! Now what? Where should you look for the “infection”? Here's a step-by-step guide on how to fix a hacked WordPress site.
And it goes without saying that the very first step to take is to:
Keep calm!
Next, you'll need to figure out how precisely that malicious individual has found his/her way into your site. What security vulnerability has he detected and exploited?
Once you've determined how your WordPress website's got hacked, figuring out how to remove the malware is already a half-solved problem.
So, let's dig in before this hypothetical infection has spread out throughout your entire website:
Step 1: Identify the Hacked Files (and Change Your Password)
Remember what we've already agreed upon, that the very first step to take is precisely not to panic?
So, while keeping your cool, start your “investigations” by asking yourself 3 key questions — this, of course, after you've already asked yourself “How to remove malware from my WordPress site?”:
Are you able to access your admin panel?
Is your site already marked as insecure (by Google)?
Is your site redirecting automatically to another website once you log yourself in?
At this point, I also strongly recommend that you changed your password, as well. And this before you jump to the next step of your investigation.
Note: remember to change it again after you've cleaned up your website, as well.
1.1. Give Your Site a Thorough Scan Using a Security Tool/Plugin
And I do think that it never gets redundant for me to stress out:
Turning on a powerful WordPress security plugin on your website is one of the best shields that you could activate around it.
In case of an emergency situation, like this one here, you'd simply enable it to scan your site remotely and track down malware locations and malicious payloads and, most of all:
A good security plugin would identify and alert you, in real-time, of all the changes made to your website.
Note: everyone knows it, yet most website owners stubbornly ignore the importance of keeping their loads of WordPress themes and plugins updated regularly. They just overlook the fact that out-of-date files are by far hackers' “top favorite” security vulnerabilities.
1.2. Check Whether Your Core Files Have Been Compromised
And since they're by far the most valuable files on your site, it's only normal to check their integrity first things first:
wp-includes
root folders
wp-admin
Most of these core files should never ever be modified.
And there are 2 ways of checking them:
you either use the diff command in your terminal
or you check them manually, via SFTP
If they're unchanged and therefore clean, move on to the next step of this “how to fix a hacked WordPress site” guide:
1.3. Check the Integrity of the Recently Modified Files
It may also be that precisely the recently modified files on your WordPress site are the “corrupted” ones.
To know for sure, identify the files that have been recently modified.
And again, you have 2 options at hand for this type of “investigation”:
the manual check
running the right commands in your Linux terminal
For manually identifying these newly changed files that might have been hacked just go through these steps here:
log into your server (use the SSH terminal or an FTP client)
if it's SSH that you're using, then it's this command that will automatically list all the files that got modified the last 15 days: $ find ./ -type f -mtime -15
if it's SFTP that you're using, just scan through the last modified date column for all files on your server
… detect any files that recent changes have been made to
Now for tracking down these possibly “infected” recently modified files using the terminal, just follow these 2 simple steps:
run this command in your terminal: $ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r
next, if you want to identify the directory files, enter this command: $ find /etc -printf '%TY-%Tm-%Td %TT %p\n' | sort -r
Are there any unexplainable changes made to those files in the last 7-30 days?
1.4. Check the Diagnostic Pages
A conveniently handy way to remove a virus from your WordPress website is to “track it down” using Google's or another website security authority's tool to give your site a deep scan with.
Has yours already been blacklisted by one of these authorities?
Then simply run the Google Transparency Report:
go to Safe Browsing Site Status website
enter your website's URL there
check both the Site Safety Details and the Testing Details sections
It's a quick and easy way to collect valuable information about any suspicious downloads, redirects, and spams on your site, as well as priceless data about Google's recent scan that ended in malware being detected.
Note: another way of identifying malware that's within your reach is by using a free webmaster tool — Google Webmasters Central, Norton SafeWeb, Bing Webmaster Tools etc.
Step 2: How to Fix a Hacked WordPress Site: Removing the Detected Malware
After all your preliminary investigations, you should put together your battle plan for actually removing the identified hack from your WordPress site. And for restoring it to its pre-hack clean state, too, obviously.
For this, here are the most effective measures at hand for you to apply:
2.1. Is a Clean Backup Available? Use It to Compare Pre-Hack to Post-Hack Files
Is there any need for me to stress out that:
You should back up your website on a daily basis!
And the very situation that you're in now is by far one of the strongest reasons to do that:
“How to fix a hacked WordPress site” will get reduced to: “simply comparing a clean backup to the current hacked version of your site!"
Identify the files that have been modified and get them removed.
It goes without saying that you risk losing some of your files — those added/updated after the last backup — but you do want a clean website now, don't you?
2.2. Remove the Identified Infected Files from Your Website
Once you've restored your WordPress backup, you can easily remove any suspicious plugin, theme or other types of file.
Note: do handle core files with utmost caution, though! Mind you don't accidentally overwrite your wp-content folder or your wp-config.php file.
When it comes to infected custom files, you could replace them with a clean recent backup or with fresh new copies.
“But how do I remove “malicious” code manually?” you might ask yourself.
Let me go briefly through all the key steps required:
log into your server (via SSH or SFTP)
back up your website
track down the recently modified files
replace any suspicious files with copies from the WordPress repository
use a text editor for opening up any custom files there and remove any suspicious code that you'll detect
test your newly cleaned up website
Word of caution: manually removing a malware infection from your WordPress site does call for special safety measures. Never remove corrupted code without first backing everything up!
2.3. Remove All Malware Infections from Your Database Tables, as Well
Now, you do agree that a “how to fix a hacked WordPress site” tutorial couldn't possibly skip the step where database tables get cleaned up of any malware infection.
Here's how you do it:
connect to your database using your database admin panel
create a backup of your database
give it a deep scan looking for any suspicious content
if detected, open the table containing that specific link or spammy keywords
manually remove that infected piece of content
give your website a “post database clean up” test
remove any tools that you might have used specifically for this operation — Adminer or maybe Search-Replace-DB
2.4. Check All The User Permissions: Look for New, Unfamiliar User Accounts
My advice to you, when it comes to user accounts, to user roles and permissions on your WordPress site is to:
Keep just one single admin user and stick to the essential user roles (and granted permissions):
author
editor
contributor
etc.
This is one of the most effective prevention measures that you could take so you don't end up asking yourself “How to clean up a hacked WordPress site?”
Now, coming back to our investigation here, here's how you remove all the unfamiliar WordPress user accounts from your website:
first, back up both your site and your database
log into your admin panel and click the “Users” tab
track down any unfamiliar new user accounts there, hover over them and delete them
Note: another wise thing to do is to re-check each user's roles and permissions. If you feel like updating them, simply use the users' role editor plugin.
2.5. Detect and “Close” all the Backdoors
And you want to treat this aspect with maximum seriousness. Otherwise, following each and every step indicated to you in this “how to fix a hacked WordPress site” tutorial becomes... pointless.
For the attackers would always have this “secret passage” to infiltrate themselves into your website over and over again.
“But what are backdoors more precisely?” you might ask yourself.
They're files similar to your site's core files — wp-config.php and key directories such as /uploads, /themes, /plugins — yet strategically placed in the wrong directories.
Here are some PHP functions that you could recognize them by:
str_rot13
assert
base64
move_uploaded_file
eval
system
stripslashes
gzuncompress
Word of caution: keep in mind that there are plugins on your WordPress website that could be legitimately be using these PHP functions; therefore, make sure you test all those "apparently suspicious changes" before rushing to remove the so-called "malicious" functions. Otherwise, by removing benign functions, you might just break your website.
2.6. Request a Review of Your Site, to Have all Malware Warnings Removed
Now, once you've repaired all the damage caused on your Wordpress site, it's only but logical to... let the blacklisting authorities know that your site's clean now.
For this, you can just request a review of your recovered website.
2.7. Change Your WordPress Salt Keys
The very last step to take in this “How to fix a hacked WordPress site” process is to change the security keys from your wp-config.php file:
This way, even if a potential attacker stole your password, he would get automatically auto-logged out once you've changed your WordPress salt keys.
Next, you can just change your password, as well as the ones of other users on your site.
Or, Just Cut All These Steps Down to a Single One: Preventive Maintenance
Which means adopting a WordPress maintenance and support plan tailored just for you and your specific security feature needs.
This way, not only that you'd save the time (and spare your nerves) that you'd otherwise invest in carrying out all the steps included in a tedious “how to fix a hacked WordPress site” process, but:
From running regular updates to on-going maintenance of your website's core components to regular security audits, you wouldn't need to... move a single finger. Our WordPress maintenance and support team would handle it for you.
“Prevention is better than cure” is so much more than just a saying...
Adriana Cacoveanu / Jun 19'2018
There's no way around it, not anymore: with Google's index now mobile-first, adopting a mobile-first approach when building a new Drupal site (or redesigning a legacy one) is… a must! It no longer depends on a specific project's needs or on the used technology. The need to develop a mobile-first content strategy has gone from particular to universal.
And facing the challenge of:
(re)creating
optimizing
structuring
… content on your Drupal website means conforming to those specific patterns that mobile users have developed for reading content on their smartphones.
In short: developing a fully responsive Drupal site comes down to centering your mobile content strategy around the idea that:
It's for the smallest screen sizes that you should plan your content for, first things first … then scale it up from there.
Now, let's see precisely what it takes to develop a mobile-first content strategy. What focus points and must-have components to include:
1. Take the Smallest Screen Size as the Starting Point
In other words: think mobile-first!
And by “mobile” I do mean “smartphones” — the smaller the screen size, the better.
This way, you'll be adjusting your content so that it makes the most of the smallest interface. Starting “small” is the best way to stick to the “keep it simple” approach:
Thinking through every content-related decision in the light of the viewport size challenge will constrain you to keep the truly essential content elements only.
Hence, this “spartan” way of eliminating the unnecessary will reflect on your site's desktop design, as well:
It will turn out cleaner and lighter.
2. Use Visual Content Wisely: Weigh Your Choices of Images
The golden rule when it comes to the imagery that you'll use on your responsive website is:
If an image doesn't enhance and complement your content, then you're better off without it!
And I know what you must be thinking:
“But people remember what they see far more easily than what they read.”
True, you need to keep in mind that visuals do come at a cost, though:
Those stunning, visually-arresting images on your website risk to divert your users' attention from the message itself.
And still, probably the most heavy-weighing reason why you should use images wisely when you develop a mobile-first content strategy is: weigh.
Visuals risk to take up valuable screen space and thus:
outshine your calls to action themselves
impact your site's overall performance (leading to frustration)
Now that doesn't mean that you should strip your content off ALL the visuals! Absolutely not!
Just to be cautious and weigh your every choice, think through your every decision involving the usage of an image.
Once you've selected the truly essential ones, keep in mind:
not to no resize them (or optimize them in any other way) before uploading them to your CMS: let Drupal do the heavy-lifting here
to leverage the Responsive Image module's (Drupal 8) capabilities for resizing them to fit the given screen sizes
3. Content Before Design
This is the right sequence to follow when you're designing (or re-designing) your Drupal site with mobile users in mind:
First, you create and strategically organize your content and upload it to your Drupal 8 CMS. It's only then that you focus on styling and developing a responsive and visually-striking web design.
If it's legacy content that you're dealing with, trying to convert it to mobile, the very first step to take when you develop a mobile-first content strategy is:
Removing all the design elements from your written content.
4. Create a Hierarchy of Your Calls to Action
Making the most of a small interface means also setting your priorities in terms of calls to action:
Pair each one with a corresponding objective, evaluate them all wisely, then select THE call to action that's most critical for you and place it — and it alone — above the fold.
5. Organize and Optimize Your Content for Mobile Devices
I'll briefly list all the key requirements that mobile-friendly content should meet — aspects to pay attention to when writing content for mobile devices — for I'm sure they're nothing new to you:
the phrases should be kept short and concise, thus eliminating the burden of “never-ending-scrolling”
the content should be sharp, targeted and skimmable, so users can easily “digest” it and modular, so that users can swiftly browse through it
“modular” meaning made either of multiple clear paragraphs — each one standing for one thought — or chunks of 3 paragraphs at most
6. Optimize Media, too, When You Develop a Mobile-First Content Strategy
And there are a couple of essential steps that you mustn't overlook when it comes to mobile-optimizing your media:
always go for thumbnails instead of video players that your users would have to load and thus strain on your site's valuable resources
don't ever use autoplay on your audio and video content
optimize your sound, image and video files both for large and small devices
7. Trim Down Your Navigation Menu
In other words: when you develop a mobile-first content strategy, consider simplifying your navigation to its truly essential links.
No user would gladly scan through a “beefy” navigation menu taking his device's entire screen:
flatten your navigation: stay away from the technique of piling up submenus, layers and navigation points
feel free to place the links that you'll remove on other places on your website (or even to turn them into calls to action)
8. Convert Your Legacy Content to Mobile-Friendly Content
If it's a legacy Drupal website that you need to restructure and to adapt to your mobile users' specific patterns for browsing through and consuming content on their smartphones, then it's time you:
dug into your static HTML
… and cleaned it up
And by “cleaning it up” I do mean:
removing inline media
removing the fixed-width tables
eliminating floats with content
breaking it down into skimmable chunks of content
… that can be easily structured into content fields.
The END! These are the 8 main aspects to focus on when you develop a mobile-first content strategy.
Now time to test the “saying” that:
“Creativity strives under constraints.”
… and to make the most of those small interfaces.
Adriana Cacoveanu / Jun 11'2018
“Learn from your mistakes” should be every developer's life mantra. But that doesn't mean that they should be all your mistakes, right? With a list including the most common Angular mistakes at hand, you'd get to narrow down the number of possible pitfalls that you risk falling into to the... uncommon, the less predictable ones.
So, what are the traps that Angular developers fall into most often as they build their applications?
We've run our own "investigations" for you:
gone through the code examples on the web
ran an inventory of the most frequent questions on StackOverflow
looked over some of the issues that we've knocked our heads against while working on our own Angular projects
… and trimmed down our list to 5 most frequent mistakes that Angular developers make:
1. ngOnChanges vs ngDoCheck: Misunderstanding When the ngDoCheck Gets Triggered
"I have used OnPush strategy for my component and no bindings have changed, but the ngDoChecklifecycle hook is still triggered. Is the strategy not working?"
I bet that you've stumbled across this question (maybe put into different words) on various developer forums. It could easily win any “popularity” test there since it keeps coming up again and again.
But, before we give it a straight answer and settle this matter for good, let's focus on these 2 “change detecting” lifecycle hooks in Angular. And see where the problem stems from:
As you well know it, AngularJs has the watch feature, which “alerts” you whenever a value changes. Angular, on the other hand, has replaced the watch and scop feature with component inputs as properties. Moreover, it has added the ngOnChanges lifecycle hook, as well.
And here's where things get “tricky” and risk to turn into the trap that many Angular developers fall into:
The OnChanges event doesn't emit if/when a deep field of the input property changes. Hence, the value of the input is the reference of the object.
How do you approach this problem? You have several methods at hand, in fact, but I'm going to focus on the most common one:
Using the ngDoCheck lifecycle hook once you run the change detection process!
Now here's the answer that I've promised, to the above-mentioned common developer question:
The onPush strategy for detecting changes in Angular does work: the hook is triggered by the design itself!
Note: another ridiculously frequent mistake that developers make is to take "Angular" for "AngularJS"! Be better than that: the term "AngularJS" should be used only when you refer to the old Angular and to Angular 1, while Angular 2/2+ 4 and 5 is just... "Angular". Mind you don't delve deep into this confusion yourself, too!
2. Forgetting to Unsubscribe: One of the Most Common Angular Mistakes
“Forgetting” or simply ignoring this issue.
And you have no “excuse”, you know, for overlooking to clean up your subscriptions in Angular. Considering that there are methods and libraries developed precisely for handling these unsubscriptions once you've finished using an event or an observable in JavaScript.
Why does this “clumsiness” risk to grow into a major issue? Because lingering subscriptions cause memory leaks in your system.
And when it comes to the unsubscription process, there are 2 scenarios:
you trigger the OnDestroy lifecycle hook if it's in a component that you've subscribed in
you initiate the lifecycle hook yourself if it's a service that you've subscribed in (since, in this case, there's no available hook for you to fire)
To recap: Remember to unsubscribe when you no longer use a service/component!
3. The Wrong Use of Providers
One of Angular's (compared to AngularJS) key improvements is its Hierarchical Dependency Injection, agree?
This means that now you're free to instantiate a service several times (services used to be singletons back in the AngularJS's “glory days”, remember?).
Now that being said, let's have a look at a more than likely scenario:
Imagine yourself fetching your heroes using a heroes service:
@Injectable()
export class HeroesService {
heroes: Hero[] = [];
constructor(private http: Http) {
this.http.get('http://give-me-heroes.com').map(res => {
return res.json();
}).subscribe((heroes: Hero[]) => {
this.heroes = heroes;
});
}
getHeroes() {
return this.heroes;
}
}
Nothing unexpectedly wrong till here:
the data is being fetched in the constructor
there's also a getHeroes method for retrieving the heroes
Now, let's take a look at the hero component, too:
@Component({
selector: 'hero',
template: '...',
providers: [HeroesService]
})
export class HeroComponent {
constructor(private heroesService: HeroesService) {}
}
@NgModule({
declarations: [HeroComponent]
}
export class HeroesModule { ... }
As you can see, first the HeroComponent declares the HeroesService provider in the @Component.providers array, next it incorporates it in the constructor.
All well and good till you realize that each HeroComponent instance instantiates a new instance of the HeroesService.
To put it more simply:
Your HeroesService will be fetching the data (by HTTP request) several times, for each and every HeroComponent instance!
And this is due to the Hierarchical DI in Angular.
The solution for avoiding this issue — no doubt one of the most common Angular mistakes?
Declaring the service in the @NgModule.providers instead:
@Component({
selector: 'hero',
template: '...'
})
export class HeroComponent {
constructor(private heroesService: HeroesService) {}
}
@NgModule({
declarations: [HeroComponent],
providers: [HeroesService]
}
export class HeroesModule { ... }
There! The provider will now be instantiated once and for all. “For all” the HeroComponent instances I mean.
“How come?” You might ask yourself.
Because the provider (declared in the NGModule now) is a singleton now. Therefore all the other modules can use it.
4. Manipulating the DOM Directly
Although I've already said this about another mistake from this list, I now tend to consider this one here instead as being one of the most common Angular mistakes:
Manipulating the DOM directly; oftentimes from the controller itself!
And this is one of those top 10 Angular mistakes that any developer stands a high risk of making. Since manipulating the DOM is such a common task when using this platform:
you might need to render SVG
you might need to refresh a page's title based on a context change
you might need to set the focus on a control after a validation error
… and the list of possible situations goes on
Then... you fall right into it: you take the easy way out and hack the DOM directly!
Now what I feel like pointing out it here is that:
Angular's grown from a web framework into a platform!
And this can only mean that you're now free to decouple your Angular application's codebase from the renderer and:
have your app executed in on the server
… in the browser
… as a native app
And decoupling opens the door to other possibilities for you to explore and to tap into, such as using web workers or AOT (ahead of time compilation).
Speaking of the latter:
AOT enables you to compile your app's templates in the build time of your server. Moreover, you won't need to use the oversized @angular/compiler package in your bundle, which leads to a lower size and load time.
Yet, for future-proofing these “facilities” that Angular provides, you'll need to abide by... some sort of rules at least. And one of them is:
Restraining yourself from manipulating the DOM directly, using jQuery, the global document object or the ElementRef.nativeElement.
Instead, use the Renderer2 service (or Renderer for Angular 2):
It's 2 things that this wrapper to the view mutation layer will enable:
for the default layer to be used in the browser
for the renderer to get replaced with a more suitable one whenever your Agular app runs on another platform (e.g. a phone)
In short: Resist “temptation” and never ever touch the DOM directly!
5. Declaring The Same Component in More than Just One NgModule
And declaring a component in multiple NGModule-s is one of those most common Angular mistakes that end up throwing an error “at” you.
“Why, so?”
Because you need to declare each component in its own NgModule — and to list it in the @Ngmodule.declarations array — in order for it to be available for the views.
If you do need to declare the very same component in multiple modules, you'll need to consider the relationship between those modules:
Is it a parent-child one, maybe?
If this is the case, then:
use the child's NGModule.declaration to declare the HeroComponent in the child module
use the chid's NGModule.exports array to... export the HeroComponent
use the parent's NGModule.imports array to import the child module
If not (if we can't be talking about a parent-child module relationship), then you'll need to declare another NgModule as the module of the shared data.
Final Word
It's only by knocking your head against unexpected issues while building your projects on this platform, that you'll get to grow as an Angular developer.
And still, instead of embracing the “fail fast, fail often” concept, wouldn't it be best if you:
learned from other developers' mistakes, thus knowing what the most common Angular mistakes are
ensured that you failed "rarely" instead?
RADU SIMILEANU / Jun 05'2018