Thursday, March 5, 2020

Parcel building with relative asset paths when using react-router

Leave a Comment

Problem:

You want to create a production build that can be uploaded in any folder, so it will work whether you upload it to site.com or site.com/app.

You use react-router in your app, so you also have to make sure that when you refresh a page, let's say site.com/contact-us it will still load the index.html from the correct location. The solution for this is usually to have a .htaccess file to load index.html whenever we try to load a path that doesn't exist:
RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

Solution:

Step 1: Build parcel with relative asset paths, using --public-url ./:
parcel build src/index.html --no-source-maps --public-url ./

Step 2: The above rewrite only fixes loading the index.html file from the correct location, we still have to make sure all the other assets are loaded relative to your .htaccess file path. To do that, we load any missing file to our target folder:
# If we try to load a missing resource file, load it from folder root
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^.*\.(jpg|css|js|gif|png|ico|mp3)$ [NC]
RewriteRule .+?([^\/]*\.*)$ $1 [L]

Step 3: Unforunately so far I don't have a solution for setting a relative path for react-router, so you still have to manually set the public url:
export const browserHistory = createBrowserHistory({
    basename: '/app'
});
This makes sure that when you have a router link to /contact-us it will actually link to /app/contact-us.
The good part is this path will only be referenced once in your build code, so you can easily change it by replacing that string even after the build was done.

Final .htaccess:

Those are the rewrites that make sure your index.html and assets are loaded correctly, even when you move your built app into a different folder.
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# If we try to load a missing resource file, load it from folder root
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^.*\.(jpg|css|js|gif|png|ico|mp3)$ [NC]
RewriteRule .+?([^\/]*\.*)$ $1 [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

I am still thinking of a solution for using a relative basename in react-router, so that way links will also be correct when placed in any subfolder or subdomain.
Let me know if you know a way to use a relative basename for browserHistory.

Later edit: A hacky solution for relative basename

I did manage to figure out a dynamic solution for having a relative basename. It's based on the idea that once our app loads, we could detect the base folder based on the current location.pathname.
I know all the possible start values for all my Routes, which in my case are /sites or /settings. Once we know this, we can safely say that anything that is before those strings in the URL is the base path of our app.

const possibleStartPaths = ['/sites', '/settings'];
// Select everything in the pathname that appears before those strings.
// For example /subfolder/myapp/sites returns /subfolder/myapp
const baseMatch = window.location.pathname.match(
    new RegExp(`(.+?)(?:${possibleStartPaths.map((x) => x.replace('/', '\\/')).join('|')})`)
);
const basename = baseMatch ? baseMatch [1] + '/' : window.location.pathname;
export const browserHistory = createBrowserHistory({ basename });
Read More...

Monday, March 2, 2020

Detect Locale Change in React i18next

Leave a Comment
I was looking for a way to re-render Chart.js charts when the react-i18next locale was changed. Looking through their documentation at https://react.i18next.com/ I didn't see any hook that could be used to detect current locale.

Problem

When the translation language is changed I also change the moment.js locale for my time-series charts in Chart.js. I need a way to detect language changes so I can rerender the charts.

Solution

Add the locale ISO code into the translation files and use that.
What I did was:
  1. Add a new translation key in my translation files: 'current_locale': 'en' for the English translation, 'current_locale': 'ro' for Romanian.
  2. Use the useTranslation() hook:
    const { t } = useTranslation();
    
  3. Rerender the chart when language is changed:
    useEffect(() => {
       // This will be now called when the locale is changed
    }, [t('current_locale')])
    

Improvements

You can also create a custom hook if you want:
export const useLocale = () => {
    const { t } = useTranslation();
    return t('current_locale');
};
Now you can use the locale value directly:
const locale = useLocale();
useEffect(() => {
   // This will be now called when the locale is changed
}, [locale])

Read More...

Friday, February 28, 2020

Finally switched to HTTPS!

Leave a Comment
Switching this blog to HTTPS took a lot longer a was harder than expected due to some Blogger bugs. The Google rankings were hit hard because the blog was not served over HTTPS, this made me spend more time and look for a solution.


Blogger: Whoops, that's an error! (bX-2kvjq7)

I have tried switching this Blogger site to HTTPS multiple times, but it never worked because whenever I switched HTTPS Availability to Yes in the settings I got this error: Whoops, that's an error! (bX-2kvjq7).




The actual problem: domain validation

The solution in my case was to remove the custom domain name, add it again and complete the DNS  validation process using the CNAME and TXT entries.
To remove your domain name go to Settings -> Basic -> Publishing -> Edit and delete the domain name and save.


After that I could enable HTTPS Availability without any error.

While writing this post things broke again

While taking the above screenshots I disabled HTTPS availability, after turning it on again the blog was stuck in a permanent 301 redirect loop, leading to ERR_TOO_MANY_REDIRECTS.
I do use Cloudflare on top of my Blogger blog, but this happens probably because of some Blogger bug and compatibility with Cloudflare.

I was not able to fix this redirect loop while keeping HTTPS availability to Yes, but after switching it to No I just enforced the Always Use HTTPS rule in Cloudflare and now it seems to work.

This solution might also work for other error codes such as bX-aa1bde or bX-gtb2wc.


Read More...

Monday, June 19, 2017

Why LiveCoding (now LiveEdu) failed

9 comments

Inception

For those who don't know livecoding.tv first started as a live streaming platform for software development (think of it as twitch for programmers). Initially, I was really excited about this idea and I have even been streaming on the site for 111 hours gathering approximately 100 followers. I wasn't the best streamer, my mic was bad, I seldom talked but the projects I showed were interesting to create and watch.

No one was earning money at the beginning (not streamers, nor livecoding), but if I recall correctly they soon added a "recruiter" plan which might have lead to some earnings for the platform. 

Time to make money!

So far so good, the community was growing, more and more streamers came to the site (even though they weren't earning anything) and viewers were interested in this idea.

It then all went downhill.

They soon added a "PRO" plan so that streamers could stream "premium content" that only PRO users could watch. It was good on paper, but they made two big mistakes:
  • The price of $25/mo was way too high in my opinion and they were referring to it as a "no-brainer". 
  • The percentage that the streamers got from those $25 was not that great. It was zero. This is where probably a lot of streamers (even though they were not earning anything until then) felt used as they were the ones providing the content but they were not receiving anything in exchange.
I recommend reading this discussion in the comment section where they announced the PRO plan. The main issue that I see in their attitude is that they thought it was fine to put themselves above the streamers. Deciding that a source of income is needed while ignoring the content creators was justified by saying "don't worry, we will care about you in the future!".

Why pivot if it's going well?

After they reduced the PRO plan to $9.99 and genuinely seemed interested about the streamers, they made the bold move of rebranding livecoding.tv to liveedu.tv. If you ask me, this is by far the biggest mistake they made. I don't know their reasoning, but it was probably related to making the platform more general, an educational platform not necessarily for coding. They seem to try turning the platform more into a directory of premium videos (udemy?). If that's the case, why keep the live in the name? 

The name livecoding was actually a good website name: memorable, easy to pronounce, easy to write and it was accurately describing what the site was about.

Current issues

I will name a few issues that really stop me from using or recommending liveedu.tv anymore, but first let's see how friendly is it for new users.

I tried today accessing liveedu.tv to see if it's worth going back.  I clicked to watch the stream featured on the homepage.


Most users leave when they see this, but I added the site to the ad-blocker exceptions. 


If I were a new user I might have left immediately not wanting to waste time creating a new account. Luckily I was an old user so I logged into my existing account (well, it wasn't that easy, because they changed their domain and my password manager did not autofill my credentials and I had to go search for it).
After I logged in I got the same screen as above but saying "SOMETHING WENT WRONG",  message which seems to show on some streams.

Now, a list of other issues that just makes me wonder how a good idea turned out so bad:
  • The interface is a mess. The site is very "jumpy", meaning that the entire layout is recalculated several times during page load as some elements are dynamically added but without having their space allocated beforehand. They are still updating it, but it seems to be for the worse. For example, I let you judge the way white space is used in the new chat section...

  • You can't really watch content if you are not a PRO member. There are 15s ads before starting to watch any stream and too many banners, sections and pages asking you to go "PRO".
  • At the time of writing this post, there are only 4 streamers online and I can't even get to load two of them.
  • Twitch now has a programming community.

Conclusion

I have only described the bad parts that I see, feel and felt from my perspective, the perspective of a streamer and occasional viewer. Let me know if you think I have been to harsh judging this site , site behind which is probably an amazing team of developers.

In conclusion, for me LiveEdu.tv is a platform that is too bulky, difficult to use and lacks enough good content to be worth using. I really wanted to see again and interact with the old spirit of LiveCoding.tv, a lean platform on which both the viewer and streamer are respected, but that spirit seems to have been stolen by the Greed Monster.

PS: LiveEdu might actually be a success and their premium projects directory might have a bigger community than I expect, but I have not yet had any contact with that side of the platform.

Later edit (20 June): LiveEdu just released a blog post introducing the new subscriber plans AND limiting the amount of content you can watch for free. I don't understand why they keep focusing on pricing instead of the content.

Date: 19 June 2017
Read More...

Saturday, April 15, 2017

Best way to withdraw money from your Envato earnings

2 comments

So, you are an author on Envato, you earned some money and you now want to make use of it!

There are a few questions you have to ask before deciding what withdrawal method to use:

  1. Do I want the money cash, in my bank account or just want to spend them online?
  2. In what currency do I want the money?
Envato supports four withdrawal methods PayPal, Skrill, Payoneer and SWIFT.

As I am from the EU and Skrill and Payoneer are not very popular here. Because of this and because they don't clearly state their rates/fees (although on some pages they take a percentage of 1.5% - 4% of the amount you withdraw) I decided not to try those so I won't say anything about them. If you had a good experience with any of those two let me know in the comment section.

TL;DR:


  • Use PayPal if you are in the US.
  • Use PayPal if you want to spend the money online.
  • Use SWIFT Bank transfer if you want to withdraw a large amount (over $1000)
  • AVOID PAYPAL CURRENCY CONVERSIONS as much as possible
  • If you withdraw a smaller amount (under $500) it might be worth to withdraw to PayPal and from there to your credit card/bank account and just accept the currency conversion fees.
  • If you want to avoid PayPal you might want to consider keeping the money into your Envato account and only withdrawing it via SWIFT once you reach $600-$700 or more.


1. PayPal

PayPal is definitely the way to go if you just want to spend the money online (most websites accept PayPal) or if you are from the US. If you have $350 in your Envato account, after withdrawing them to PayPal you will have exactly $350 in your PayPal account that you can spend online with ZERO taxes.

PayPal has usually no fees for transfers BUT, only if there is no currency conversion involved. If there is any currency conversion God help you.

Let's say you have $350 in your PayPal account and you want to withdraw them to your bank account. There are actually two withdrawl methods: to credit card or directly to your bank account.

 a. Withdrawing to your VISA Credit Card

  • Fee: $2.50 USD - This is a flat fee for any amount you withdraw. This is the only fee.
  • Limit: $500 (daily) - Note that in some countries this limit might not exist, not so sure about it, but in most cases it's $500
  • Note: You first have to confirm your card to be able to withdraw.

 a. Withdrawing to your Bank Account

  • Fee: Zero 
  • Limit: None
  • Note: You still have to confirm your card or bank account to be able to withdraw money.
All seems great, but, as I previously said, there's a catch: currency conversion.

Well, I told myself, I will just open an USD bank account at my local bank and I will withdraw the USD in my PayPal account to my USD bank account at zero cost and with zero currency conversions.

Unfortunately it doesn't work like this: PayPal only allows to withdraw to a bank account only in your local currency*. 
*(funny thing, my local currency is RON, not EUR, but PayPal decided to use EUR)

When I tried to withdraw USD (PayPal) ---> USD (my Bank) PayPal actually showed that the transfer will look like this:
USD (PayPal) --> EUR (conversion, by PayPal) --> USD (another conversion, my Bank)

Now, what you have to know about the PayPal conversion rates is that this is how they make their money: they add another 2.5% - 4% on top of the current market exchange rates. So, if I were to withdraw $350 USD to my USD bank account I will receive around 317 EUR (at today's exchange rate -4%) which will then be converted again to USD by my bank. Assuming that the bank uses a fair exchange rate I will actually have in my bank account around $335 USD. So, although there are 0 transfer fees I would lose around $15 due to PayPal's exchange fees.

I tried contacting PayPal in order to update my account to be able to tansfer USD to USD without the additional USD->EUR conversion but they said it is impossible for bank accounts but, if I have a credit card attached to my USD bank account they can update the currency for the credit card for me so I can withdraw USD->USD with no extra conversion. As good as this sounds, for me there are two issues:
  1. The $500 daily withdrawal limit still applies, so if I would ever want to withdraw more than that I would have withdraw multiple times, in different days and with each withdrawal there will be the $2.50 withdrawal fee.
  2. Even with the limitations above, that would still be the best method for me as I don't regularly earn more than $500 monthly on Envato so one withdrawal would be enough. Why I can't use that method is simply because my bank does not offer credit cards for USD bank accounts, so I can not have a VISA credit card attached to my bank account.

Note that those fees might differ in your country, make sure to check the PayPal withdrawal fees page.

2. SWIFT

SWIFT is the most popular international payment network for transferring money between different banks, be them in different countries or not. There are no percentage charges for the amount you transfer but a flat amount of $25 (might depend based on your country/bank). 

Envato charges $25 from the start to cover their bank costs, as the SWIFT transfer fees can be paid by the sender, the receiver or split between them (I think that fee should cover the entire transfer cost for most banks/countries). Unfortunately in my case, being from Romania and Envato sending the money from US I got charged another $25 (leading to a total of $50 transfer fee), probably by an intermediary bank, but I can't tell for sure as there is no evidence that those missing extra $25 have ever been sent. 

So, in my case, I withdrew $600 but I only received $550 in my bank account. As I did not have an USD bank account that sum got automatically converted at an acceptable (actually good) exchange rate, to my local currency RON.

Now, if you are from the US or in a different country and maybe just by using a different bank I think the total SWIFT transfer fee should only be the $25 that Envato charges.

So, what withdrawal method are you using?

Well, I am still looking for the "best way", but as of now I am just withdrawing from Envato->PayPal and then from PayPal to my credit card, in my local currency so only one conversion happens, not two. This still means that if I ever need to withdraw more than $500 in a month I would have to make multiple withdrawals, each one with a $2.50 fee. 
I would withdraw from PayPal to an USD credit card, unfortunately my bank doesn't offer those.

Suggestions please!

If you know a better withdrawal method or if you found that in your country a specific way of withdrawal works better, help others by describing your experience in the comments.

Disclaimer: I am just an author on the CodeCanyon marketplace, I am not related in any way with the Envato company.

Have a lovely day!
Cristy.


Read More...

Sunday, March 12, 2017

Road to 10k - Prologue - Thoughts of an author

Leave a Comment

What is "Road to 10k"?

This is the first post from a new blog series called "Road to 10k" in which you can follow my thoughts, hopes, progress, disappointments and cool solutions for problems encountered while creating and updating multiple web applications in order to reach 10,000 sales on CodeCanyon. My intention is to reach 10,000 sales by the end of this year (2017).

In other words you will read about Web Dev, JavaScript, algorithms, app performance, marketing and some occassional cursing.

Initial state


As you may or may not know, my main income source is my userTrack script that I have created in 2013 and updated regularly ever since. I have recently reached 1000 sales in my 5 years of being an author on CodeCanyon, meaning that making another 9000 sales in the 9 months left in this year would be an increase of 60 times the amount of sales I do each month.

So, what's the plan?

In order to increase my sales I have planned to do the following:
  • Create more items. I plan on creating a new product at least once every month, so by the end of the year I should have at least 10 different items in my portfolio.
  • Marketing. Although userTrack is a great script and offers good value for money, not many have heard of it because I have failed reaching out to enough webmasters, even though I tried anything from paid advertising to contacting bloggers. I suck at marketing. So, my plan in this direction is to either find someone who is really good at marketing or take more time doing content marketing (creating tutorials on how to use my items, creating guest posts explaining why they make your life easier or why are they a great piece of software).
  • Be more professional. As of now, every customer who has an issue can either contact me via the comment section of my items or via e-mail. Although this works good enough for now this is not scalable. Not only I can not keep track of opened issues if there are more than 2-3 customers complaining at once but also I can not verify their support period. On CodeCanyon the price of the item is actually composed of two things: item price and support price. When you purchase an item you get 6 months of support from the author, after this period you have to extend it (which costs about 50% of the item list price) or the author is no longer required to answer your support questions. This means that at the moment there are many customers who get support from me for free, even though their support period expired. To solve this issue I will switch from using the mail-support I do today with a web ticket system that requires the customer to verify their support period before creating a new ticket. This will not only increase a bit my revenue by making sure customers have valid support but will also help with scalability, organizing the support tickets and making sure each and every customer has his issue resolved (no more spam folder e-mails, no more accidentally marking an e-mail as read).
I start today: I have already submitted a new item for review on CodeCanyon. I will write a post about it and some cool Web Dev tricks I used to create a smooth UX a few weeks after it will be accepted and up for sale (so that I can also provide some sales numbers).

Let me know if you have any questions about me, my very ambitious plan, userTrack or any Web Dev related question in the comment section below.

So our journey begins, make sure to check the blog once or twice a month to see how my progress goes and whether I am heading in the right direction or went crying in a corner while re-thinking my life.

Author: Cristian Buleandră
Date: 12th March 2017
Read More...