Kategorier
Code

Quick tip: .env in next.js

Using environment variables is a great way to store environment specific values and secrets that should not be in the git repo.

Lets say you have an API which runs on localhost locally but a different host in production.

On the server

Locally you need to add an .env.local-file in your project root containing a variable for the api host name, lets call it API_HOST and point it to localhost port 8080.

# .env.local in project root
API_HOST=http://localhost:8080

You would then need to add the environment variable to your production env as well. This will look different depending on your hosting provider but on Google Cloud Run it looks like this:

On the client

To expose your environment values to the client, you need to add them to your next.config.js

In most cases keeping using the variable on the server is enough, but in some cases you might need to access the environment variable on the client as well and in those cases you need to add the variable to your next.config.

// next.config.js
module.exports = {
  env: {
    API_HOST: process.env.API_HOST
  }
}
Kategorier
Code Frontend

CSS modules in next.js

On bergqvist.it I used styled jsx for styling my components. I preferred that to other css-in-js frameworks (like JSS) because of it actually using CSS syntax instead of JavaScript objects.

// styled jsx example with good old CSS
<style jsx>{`
  .label { color: red; font-style: italic; }
  .article { padding: 0; }
`}
</style>

//JSS example with CSS as a JS object
const useStyles = createUseStyles({
  label: {
    color: 'red'
    fontStyle: 'italic'
  },
  article: {
    padding: 0
  }
})

I like Styled jsx but it has had an issue with FOUC in the last few versions of Next.js though, and with Next 12 I decided to try something new and migrate to CSS Modules instead.

What is CSS Modules?

CSS Module is a CSS file in which all class names and animation names are scoped locally by default. 

So the benefit are the same as css-in-js-frameworks but pure css (or in my case scss) files are used instead of keeping the styling in the javascript files.

Read more about CSS Modules here

Why CSS Modules?

I may be old school, but I actually prefer to keep the CSS and JavaScript separated for each other. I can see the benefits of keeping them tightly coupled and can agree that simple, self-contained components probably benefit from this approach, but it gets messy when the component has many styles with media queries.

I also want to use SASS, which is fully supported with CSS Modules in Next.js.

Migrating from styled jsx to CSS Modules

Since Styled jsx use regular CSS it’s actually just a matter of creating the <component>.module.scss-file, importing it into the component and changing the classes

//styled jsx
export default function MyComponent(){
  return (<div className={"article"}>
    <span className={"label"}>...</span>
    <style jsx>{`
      .label { color: red; font-style: italic; }
      .article { padding: 0; }
    `}</style>
  </div>)
}

//CSS Modules
import styles from "./MyComponent.module.scss";

export default function MyComponent(){
  return (<div className={styles.article}>
    <span className={styles.label}>...</span>
  </div>)
}

Using multiple modules in one component

For reusability you might want to use a css module in more than one component


import styles from "./MyComponent.module.scss";
import * as secondaryStyles from "./secondary.module.scss";

export default function MyComponent(){
  return (<div className={styles.article}>
    <span className={secondaryStyles.label}>...</span>
  </div>)
}

If you are using TypeScript this approach probably cause an error: TS2339: Property 'label' does not exist on type 'typeof import("*.module.scss")'.

The error can be can be mitigated by adding a typings.d.ts -file to the root of your project with the following content

// typings.d.ts
declare module "*.module.scss" {
  interface IClassNames {
    [className: string]: string;
  }
  const classNames: IClassNames;
  export = classNames;
}

Composition

Instead of importing several different modules it’s possible to compose new classes from existing classes.

// secondary.module.scss
.label { 
  color: red; 
  font-style: italic; 
}

// MyComponent.module.scss
.article { 
  padding: 0; 
}
.label {
  composes: label from "./secondary.module.scss";
}


// MyComponent.tsx
import styles from "./MyComponent.module.scss";

export default function MyComponent(){
  return (<div className={styles.article}>
    <span className={styles.label}>...</span>
  </div>)
}

Global styles

As I already had a global css-file that I imported into my _app.tsx, I really did not have to do anything to get my global classes working.
If you want to add a global class in a component file you can add it by using :global() on the class.

:global(.label) { 
  color: red; 
  font-style: italic; 
}

Parting words

I’m quite happy with CSS Modules, the site no longer gets FOUC and it looks great with JavaScript disabled as well!

Hope this could be of any help to someone looking into CSS Modules.

Kategorier
Frontend

How to add an RSS-feed to your Next.js site

I love RSS-feeds (and still curse Google for cancelling Google Reader) and use them as my main news source for things I find interesting so with this article I would like to help people to add RSS-feeds to their blogs.

If you read my article about how to add a sitemap.xml to your next.js site you will recognise much of the code, it’s pretty much the same base but with slightly different XML-markup.

Creating the page

First off we need a page that can return the XML. I suggest you name it ”rss”, ”feed” or something similar.

In getInitialProps we get our blog posts and set the ”Content-Type”-header to ”text/xml” so the browser knows that should expect XML instead of HTML.
We then generate the XML and passes it on to the browser using res.write.

export default class Rss extends React.Component {
  static async getInitialProps({ res }: NextPageContext) {
    if (!res) {
      return;
    }
    const blogPosts = getRssBlogPosts();
    res.setHeader("Content-Type", "text/xml");
    res.write(getRssXml(blogPosts));
    res.end();
  }
}

Generating the base XML for the feed

For the base XML document you will need to add some basic information like the title of the log, a short description, link to your website and the language of the content.
Title, link and description are mandatory elements in the RSS specification but add as many optional elements as you find useful.

const getRssXml = (blogPosts: IBlogPost[]) => {
  const { rssItemsXml, latestPostDate } = blogPostsRssXml(blogPosts);
  return `<?xml version="1.0" ?>
  <rss version="2.0">
    <channel>
        <title>Blog by Fredrik Bergqvist</title>
        <link>https://www.bergqvist.it</link>
        <description>${shortSiteDescription}</description>
        <language>en</language>
        <lastBuildDate>${latestPostDate}</lastBuildDate>
        ${rssItemsXml}
    </channel>
  </rss>`;
};

Adding XML for the blog items

With the basic stuff out of the way all we need to go is generate some XML for the blog posts and figure out when the blog was updated.

The item element should at least contain a link to the blog post, the date when it was published and the text. You can either opt to put a short description and force the user to come visit your page or put the whole post in the XML.

If you have HTML-markup in your text you need to enclose it within a <![CDATA[${post.text}]]>-tag or HTML encode the text.

const blogPostsRssXml = (blogPosts: IBlogPost[]) => {
  let latestPostDate: string = "";
  let rssItemsXml = "";
  blogPosts.forEach(post => {
    const postDate = Date.parse(post.createdAt);
    if (!latestPostDate || postDate > Date.parse(latestPostDate)) {
      latestPostDate = post.createdAt;
    }
    rssItemsXml += `
      <item>
        <title>${post.title}</title>
        <link>
          ${post.href}
        </link>

        <pubDate>${post.createdAt}</pubDate>
        <description>
        <![CDATA[${post.text}]] >
        </description>
    </item>`;
  });
  return {
    rssItemsXml,
    latestPostDate
  };
};

Finishing up

The last thing you need to do is to add a link to your feed somewhere in the head of your document.

<link 
  rel="alternate" 
  type="application/rss+xml" 
  title="RSS for blog posts" 
  href="https://www.bergqvist.it/rss" />

This will make it easier for browsers and plugins to auto discover your feed.

The code is available as a gist on github and please leave a comment with any feedback.

Kategorier
Frontend

Adding a dynamic sitemap.xml to a next.js site

While building my blog with Next.js I naturally wanted to support sitemaps because it can supposedly help out the search engines. For my small blog it will not make any difference but for larger sites it’s more important. Google has this to say.

Using a sitemap doesn’t guarantee that all the items in your sitemap will be crawled and indexed, as Google processes rely on complex algorithms to schedule crawling. However, in most cases, your site will benefit from having a sitemap, and you’ll never be penalized for having one.

Page for the sitemap

The first thing we need to do is to create a sitemap.xml.ts page in the ”page”-folder. This will expose a https://yourdomain.com/sitemap.xml url that you can submit to search engines. if you want to you can omit the .xml part and only use /sitemap, Google search console will accept the url anyway.

We want to make sure that we set the Content-Type header to text/xml and to write our xml output to the response stream.

export default class Sitemap extends React.Component {
  static async getInitialProps({ res }: any) {
    const blogPosts = getBlogPosts();
    res.setHeader("Content-Type", "text/xml");
    res.write(sitemapXml(blogPosts));
    res.end();
  }
}

Generating the base xml

For the site map we want to list all pages on the site, apart from the blog posts we have to add all additional pages that we want the search engines to find.

I have an about page that I add manually together with the index page but if you have many pages I suggest you create an array and add them in a more automated way.

I won’t go into the inner workings of all the properties of a sitemap but I want to mention the <priority>-tag that lets you set a value between 0 and 1 indicating how important you think the page is.
<lastmod> is used to indicate when the page was changed.

const sitemapXml = (blogPosts: IBlogPostListItem[]) => {
  const { postsXml, latestPost } = blogPostsXml(blogPosts);
  return `
  <?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>https://www.bergqvist.it/</loc>
      <lastmod>${latestPost}</lastmod>
      <priority>1.00</priority>
    </url>
    <url>
      <loc>https://www.bergqvist.it/about</loc>
      <priority>0.5</priority>
    </url>
    ${blogPostsXml}
  </urlset>`;
};

Adding xml for the blog posts

As mentioned above I want to add the dynamic blog post pages to the site map as well. In the blogPostsXml-function I generate xml for all posts and keep track of when the latest post was posted.

const blogPostsXml = (blogPosts: IBlogPostListItem[]) => {
  let latestPost = 0;
  let postsXml = "";
  blogPosts.map(post => {
    const postDate = Date.parse(post.createdAt);
    if (!latestPost || postDate > latestPost) {
      latestPost = postDate;
    }
    postsXml += `
    <url>
      <loc>${post.url}</loc>
      <lastmod>${postDate}</lastmod>
      <priority>0.80</priority>
    </url>`;
  });
  return {
    postsXml,
    latestPost
  };
};

Last words

Make sure to check that you do not add any pages to the sitemap that is blocked in your robots.txt.

If you have a large site with many pages (100 or more) you can split up the sitemap into several smaller ones, for very large sites this is a must!

I hope this could help out someone and please leave a comment. A full gist of the code can be found here

Kategorier
conference

SmashingConf New York 2019

A few weeks ago I had the privilege of attending SmashingConf in New York, travelling from a chilly Swedish autumn to a quite pleasant New York end of summer. I spent the weekend fighting jet lag by taking long walks and touristing so I could be fit for the first workshop I had signed up for.

TL;DR

Great conference but not technical enough for my taste.

Watch Wes Bos’s talk (slides) for good javascript insights and all talks can be found here: SmashingConf NY 2019 videos.

Lightning fast performance with Scott Jehl.

Spending a whole day digging deep into performance sounded like a great way to spend a Monday so I had booked.
The venue for the workshop was located at Microsoft, just a short walk from my hotel so I had plenty of time to get a good nights sleep, eat a steady breakfast and still make the 9 o’clock start without any problems.

Scott Jehl was really easy going and the workshop covered tools to measure performance and how to mitigate issues.
I would however have liked more nitty gritty details and less time spent on using online tools.

The Move Fast & Don’t Break Things-talk that Scott held on the second day of the conference was a distilled version of the workshop so check it out if you’re interested.

In the evening I attended a Shopify-hosted jam session with lightning talks from Shopify, Microsoft, Forestry (about TinaCMS!) and a few others talkers.

Conference day one

The conference took place at the New world stages close to time square.
The main stage was a musical theatre which worked well but the rest of the venue was quite cramped.

Many of the talks were more of the UX/inspirational kind which can be nice, but I’m more of a hands on person so my favourites were the following.

Marcy Sutton on Garbage Pail Components is a talk about accessibility with an 80’s twist (and not even the first 80’s flashback this conference).

Wes Bos on Slam Dunk Your JavaScript Fundamentals is jam packed with new APIs that you might not have heard of yet, especially the Intl-object.

In the evening the SmashingConf party took place at Waylon bar where speakers and participants got to mingle. I met lots of friendly people from both sides of the pond and had a great time.

Conference day two

With a slight hangover and not enough sleep I went to see the mystery speaker dina Amin who makes wonderful stop-motion shorts with old discarded electrical devices.

Another fun talk was the Using a Modern Web to Recreate 1980s Horribly Slow & Loud Loading Screen-talk where Remy Sharp recreated the loading screens of his old 80’s Sinclair Spectrum computer. All ending with a photo of the audience being transformed to the Spectrum image format and shown on the big screen

Next.js with Remy Sharp

With the conference over I still had a workshop day to look forward to so I went back to the Microsoft office to learn some next.js!

The workshop was good with all the basics of next.js covered, I had already tinkered with next.js (my homepage runs for example) so most things were familiar but luckily I had not read up on the changes in 9.1 so I did learn some new tricks.

All in all I had a great week in NYC and I met lots of great people but I would have liked if the conference and workshops were a bit more technical.