Skip to content

Commit

Permalink
fix: make absolute images url works on client side
Browse files Browse the repository at this point in the history
  • Loading branch information
znarf committed May 15, 2018
1 parent 2c8f9f9 commit 283ee74
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
13 changes: 12 additions & 1 deletion src/lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { get } from 'lodash';

export function truncate(str, length) {
if (!str || typeof str !== 'string' || str.length <= length) {
return str;
Expand Down Expand Up @@ -57,6 +59,14 @@ export function getCurrencySymbol(currency) {
return r.replace(/0$/,'');
}

export function getBaseImagesUrl() {
if (process.browser) {
return get(window, ['__NEXT_DATA__', 'env', 'IMAGES_URL']);
} else {
return get(process, ['env', 'IMAGES_URL']);
}
}

export function resizeImage(imageUrl, { width, height, query, baseUrl }) {
if (!imageUrl) return null;
if (!query && imageUrl.match(/\.svg$/)) return imageUrl; // if we don't need to transform the image, no need to proxy it.
Expand All @@ -67,7 +77,8 @@ export function resizeImage(imageUrl, { width, height, query, baseUrl }) {
if (width) queryurl += `&width=${width}`;
if (height) queryurl += `&height=${height}`;
}
return `${process.env.IMAGES_URL || baseUrl || ''}/proxy/images/?src=${encodeURIComponent(imageUrl)}${queryurl}`;

return `${getBaseImagesUrl() || baseUrl || ''}/proxy/images/?src=${encodeURIComponent(imageUrl)}${queryurl}`;
}

export function imagePreview(src, defaultImage, options = { width: 640 }) {
Expand Down
14 changes: 11 additions & 3 deletions src/pages/_document.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@

import Document, {Head, Main, NextScript} from 'next/document'
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document'

// The document (which is SSR-only) needs to be customized to expose the locale
// data for the user's locale for React Intl to work in the browser.
export default class IntlDocument extends Document {

static async getInitialProps (context) {
const props = await super.getInitialProps(context);
const {req: {locale, localeDataScript}} = context;
const { req: { locale, localeDataScript } } = context;

return {
...props,
Expand All @@ -15,6 +16,13 @@ export default class IntlDocument extends Document {
}
}

constructor (props) {
super(props);
props.__NEXT_DATA__.env = {
IMAGES_URL: process.env.IMAGES_URL || '',
};
}

render () {
// Polyfill Intl API for older browsers
const scriptsUrls = {
Expand Down

0 comments on commit 283ee74

Please sign in to comment.