iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍱

Building a Tech Blog Aggregator for Team Members Using RSS and Next.js

に公開
2021/04/06
17件

I recently came across this article.

Tech blogs don't last - note.com

It's a common sight: a company starts a tech blog for recruitment purposes, but over time, it becomes filled with old articles or posts only from employees who have already left the company.

When tasks are piling up in front of you, it's quite difficult to find time to write a blog post during working hours.

That said, there isn't much motivation to write for a company blog for free outside of working hours either—especially if you have the feeling that you "might change jobs within a few years." If the articles remained yours even after changing jobs, perhaps the motivation to write would increase.


After that, I saw these tweets.

When people think of corporate tech blogs, the standard format is "the company creates one blog, and everyone posts there," but it might actually be enough to just provide a place to aggregate individual posts.

Looking into it further, HERP's tech blog is exactly like that. Members post articles to their favorite places, such as personal blogs, and the company's tech blog acts as a hub that aggregates and displays links to those articles. That's a great approach.

Created a site to aggregate team members' tech blogs via RSS

Aggregating the personal blogs of internal members by following RSS feeds is not that technically difficult. Since I've been focusing solely on developing Zenn lately, I decided to create a starter-like project as a bit of a break.


The demo site looks like this

Demo Site →
GitHub Repository →

As you can see from the demo site, it serves as an entry point that collects links to articles posted by individuals.

Each member can post to their preferred platform—such as Zenn, Qiita, Medium, note, or Hatena Blog—as their own article. As long as an RSS feed can be obtained, it's fine to post anywhere.

Technical Configuration

I used Next.js (TypeScript) to build the site. The static site is built according to the following flow:

  1. Fetch post data from each member's RSS URL.
  2. Combine the data from step 1 to create a posts.json file containing the list of post data.
  3. Build as a static site using Next.js.

Registering member RSS feeds

It's easiest to look at the source code, but it's set up so that each member's profile and RSS URL list are registered in a file called members.ts.

[{
  name: "Member Name",
  role: "Job Title",
  sources: [
    "https://zenn.dev/catnose99/feed",
    "https://medium.com/feed/@catnose99",
  ]
}]

👆 Specify the RSS URLs in the sources section. You can also specify multiple URLs.

Excluding specific articles using regular expressions

I thought there might be cases where you want to exclude (or specifically include) certain articles from the company tech blog, so I made it possible to filter them by specifying regular expressions as follows:

[{
  ...
  sources: [
    "https://zenn.dev/catnose99/feed",
    "https://medium.com/feed/@catnose99",
  ],
  includeUrlRegex: "Regex matching URLs of articles you want to include",
  excludeUrlRegex: "Regex matching URLs of articles you want to exclude"
}]

When yarn build:posts is executed, it fetches a list of post metadata from the RSS feeds based on these settings and generates a file named posts.json that summarizes the article information. Parsing RSS is easy using a package called rss-parser.

Building a static site with Next.js

Using Next.js makes it easy to create static sites. As mentioned above, since a file called posts.json containing the list of post data exists in the directory, you just need to import the necessary data from there and display it.

There's almost no need for getInitialProps or getStaticProps, which are often used when building apps with Next.js.

Deployment

The demo site was deployed to Vercel. As long as you can run npm run build (yarn build) before hosting, you can deploy it anywhere.

When operating as a team, setting up a CI/CD environment would make management easier. It's convenient for everyone if you can just ask new employees to "add your personal blog's RSS URL and submit a pull request."

In that sense, services that easily integrate with repositories like Vercel or Netlify are recommended.

Regularly automating builds

In actual operation, in order to update the list of posts, it is necessary to perform builds automatically at regular intervals (such as once a day).

  • In the case of Vercel, using GitHub Actions' "cron" makes it easy to set up periodic automatic deployments. For details, refer to the GitHub Discussion.

  • In the case of Netlify, you can perform automatic deployments using methods like Auto trigger deploys on Netlify.

License

The project I created this time is open source. Feel free to fork and use it as you like.

You might also want to use it individually, even if not as a team. For example, if you post to note, Medium, and Zenn, you can use the same mechanism to consolidate your list of posts in one place.

*Note: The first thing you'll probably want to change is the color scheme. Since I've kept the number of colors used to a minimum and manage color codes with CSS variables, it should be relatively easy to modify.

https://github.com/catnose99/team-blog-hub

Discussion

坦々狸坦々狸

質問ってここで良いのでしょうか?

私もこれを使って自分のブログを1箇所で見れるようにしてみました。

https://blog-hub.vercel.app/

ありがとうございます。

質問というのは最初の頃はうまく動いてるように見えたんですが最近zennへの投稿数と取得されてる記事の数が合わない事に気づいたのです

自分でも調べてみたのですがJS系の開発経験もなく原因がよくわかりませんでした。

私がやったのはposts.tsのfetchFeedItems関数に

posts.ts
console.log(feed?.items?.length);

を追加してビルド時に取得できた記事の数を表示させてzennの自分の記事数と比較したり

posts.ts
  const test = await parser.parseURL("https://zenn.dev/他の人のID/feed");
  console.log(test?.items?.length);

として他の人のRSSではどうかと確認したりしたんですがどちらも記事数が合わなくなってしまいました。

またrss-parserという外部モジュールが記事を認識できていないのが原因かと思い
package.jsonのバージョン指定の部分を

package.json
    "rss-parser": "^3.12.0",

に書き換えて最新のものを取得し直してみたりしましたが結果が変わりませんでした。

この段階で手詰まり状態に陥ってしまったのですが
なにか他に試せるようなことがあればご教授願えないでしょうか?

1
坦々狸坦々狸

すいません自己解決しました
zennのRSSは最新15件だけ返却されるんですね😓
自分のTOPページに出てるArticlesの数と比較してたので気づきませんでした
ふと実際のRSSのitemフィード数えたら15件だったので表示出来てました
お騒がせしました😖

catnosecatnose

ありがとうございます。

もしかするとなのですが、RSSの最大表示件数によるものかもしれません。Zennに関わらずほとんどの投稿サービスではRSSの最大表示件数が10〜20程度に制限されています。RSSリーダーが最大10程度までしかフェッチを行わないため、パフォーマンスのために制限を設ける形になっています。

ZennでもRSSに載るアイテム数は最大15となっています。noteだと25みたいですね。Zennの方でURLに?limitをつけることで最大アイテム数を変えられるようにできないか検討してみますね。

noteの方はどうにもできませんが…

1
catnosecatnose

あ、コメントを見逃していました!ちなみに、以下のURLを叩くとtantan_tanukiさんの全ての記事一覧が取得できます。jsonをいじる必要は出てきますが、それでもよければご活用ください🙏

https://zenn.dev/api/articles?username=tantan_tanuki&order=latest
4
坦々狸坦々狸

ただの勘違いだったのに丁寧な返信ありがとうございます!
全記事取得するAPIがあるんですか
フロントエンド周りはかなりスキル低いので頑張ってみます😆

2
catnosecatnose

遅くなってしまいましたが、フィードページにおいてhttps://zenn.dev/ユーザー名/feed?all=1のようにall=1というクエリ文字列を指定することで全ての投稿アイテムを出力できるようになりました。

5
坦々狸坦々狸

おぉ!ありがとうございます
こういう隠しコマンドみたいなの面白いですw

1
坦々狸坦々狸

早速取り込みました
記事数が多くなるとLOAD MOREボタンで記事追加読み込み出来るの初めて知りましたw

1
坦々狸坦々狸

何度もすいません。
記事内容と違う内容の相談になってきてしまうのですが

私の感じてた違和感がなんとなく掴めてきたのでご相談させて下さい。

https://zenn.dev/tantan_tanuki/articles/4660bcd088f5ac

この記事の内容なのですが
継続して確認していた所たまに過去のRSSが取得される事象が起きて
それが反映されているのではないかという気がします。

以下を見ていただきたいのですが

$ xmllint --xpath "/rss/channel/lastBuildDate/text()" <(wget -O - -q https://zenn.dev/catnose99/feed)
Thu, 08 Apr 2021 00:50:21 GMT
$ xmllint --xpath "/rss/channel/lastBuildDate/text()" <(curl -s https://zenn.dev/catnose99/feed)                                                                                   
Wed, 07 Apr 2021 21:15:41 GMT

丁度catnoseさんのRSSがずれていたので確認用に使わせていただきました🙇

こんな感じでcurlとwgetで同じRSSにアクセスするとかなり前のフィードが取得される事があります

curlとwgetの違いを確認した所リクエストヘッダに
Accept-Encoding:identity
が付くようでcurlにこのヘッダを付けてリクエストするとwgetと同じ記事が取れるようになったりもします。

1度発生するとこの手法で再現は結構簡単なのですがこの問題が発生する人としない人がまちまちなので確実な再現方法というのが確立できていません恐らくRSSに頻繁にアクセスされる人の方が発生しやすいのではないかと思っています。

そこで昨日一日なにも更新せずに以下のような手法で確認していたのですが

while sleep 3600;do xmllint --xpath "/rss/channel/lastBuildDate/text()" <(wget -O - -q https://zenn.dev/tantan_tanuki/feed); done

午前中は日付を跨いだ瞬間に1件だけ違うパターンが紛れ込みましたが大体1時間位ずれた2パターンのfeedがランダムに取得されるという挙動になりました。

また私ではないのですが他の人のRSSでこの揺れの間に記事を更新されている方の記事が巻き戻っている事も確認できました。(ログが残ってないので申し訳ない)

そこで更に確認のため以下のように確認してみました

$ while sleep 3;do xmllint --xpath "/rss/channel/lastBuildDate/text()" <(curl -s https://zenn.dev/catnose99/feed); done                                                         
Wed, 07 Apr 2021 21:15:41 GMT
Wed, 07 Apr 2021 14:18:55 GMT
Wed, 07 Apr 2021 21:15:41 GMT
Wed, 07 Apr 2021 14:18:55 GMT

$ while sleep 3;do xmllint --xpath "/rss/channel/lastBuildDate/text()" <(wget -O - -q https://zenn.dev/catnose99/feed); done                                                    
Thu, 08 Apr 2021 00:50:21 GMT
Thu, 08 Apr 2021 00:49:54 GMT
Thu, 08 Apr 2021 00:50:21 GMT
Thu, 08 Apr 2021 00:49:54 GMT

ここでcurlとwgetで取れる記事が違いさらにそれぞれで2パターンの記事が取得されるようですので
少なくとも4パターンのRSSが取得される可能性がありそうです。

Wed, 07 Apr 2021 14:18:55 GMT
Wed, 07 Apr 2021 21:15:41 GMT
Thu, 08 Apr 2021 00:49:54 GMT
Thu, 08 Apr 2021 00:50:21 GMT

内部の構造がわからないので憶測になりますが
この返却のパターンから考えてLBの裏に2台RSSを配信しているサーバがいて
そのサーバ毎にキャッシュされているRSSが違うのではないか?
そしてそのキャッシュはリクエストヘッダによって変わるレスポンス内容毎に別々にキャッシュを保存しているのではないか?

というのが私の見解なのですがこれ以上ちょっと調べるのが難しいのと
そもそも全然見当違いの推測をしているかもしれないので
申し訳ありませんが何かわかることがあればご教授願えないでしょうか?

2
catnosecatnose

すみません、見落としてました。
こちらのキャッシュの問題についても解消済みです。

1
うーたんうーたん

こちらのteam-blog-hubを使いたいと思い。試してみたのですが、以下のようなエラーが出てしまいました。
私の力では解決できなかったので、お力添えいただけますでしょうか。

Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
Failed to compile.
./src/pages\index.tsx:4:19
Type error: Cannot find module '@.contents/posts.json' or its corresponding type declarations.

  2 | import Link from "next/link";
  3 | 
> 4 | import posts from "@.contents/posts.json";
    |                   ^
  5 | import { config } from "@site.config";
  6 | import { PostItem } from "@src/types";
  7 | import { ScrollableMembers } from "@src/components/ScrollableMembers";
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: "build:next" exited with 1.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

npx browserslist@latest --update-dbのコマンドで解消されるか試しましたが、解消されませんでした。

1
catnosecatnose

yarn devを実行する前に一度yarn buildの実行が必要です(yarn buildを実行するとposts.jsonが生成されます)。

1
うーたんうーたん

ありがとうございます。yarn buildを実行後にエラーが出てしまいました。説明が不足していました。

エラーの内容のすべてです。

$ yarn build
yarn run v1.22.10
$ run-s build:posts build:next
$ ts-node --project tsconfig.builder.json ./src/builder/posts.ts
(node:7212) UnhandledPromiseRejectionWarning: Error: Status code 404
    at ClientRequest.<anonymous> (C:\Users\team-blog-hub\node_modules\rss-parser\lib\parser.js:88:25)
    at Object.onceWrapper (events.js:422:26)
    at ClientRequest.emit (events.js:315:20)
    at ClientRequest.EventEmitter.emit (domain.js:483:12)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:596:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
    at TLSSocket.socketOnData (_http_client.js:469:22)
    at TLSSocket.emit (events.js:315:20)
    at TLSSocket.EventEmitter.emit (domain.js:483:12)
    at addChunk (_stream_readable.js:295:12)
(node:7212) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:7212) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
$ next build
Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
Failed to compile.

./src/pages\index.tsx:4:19
Type error: Cannot find module '@.contents/posts.json' or its corresponding type declarations.

  2 | import Link from "next/link";
  3 | 
> 4 | import posts from "@.contents/posts.json";
    |                   ^
  5 | import { config } from "@site.config";
  6 | import { PostItem } from "@src/types";
  7 | import { ScrollableMembers } from "@src/components/ScrollableMembers";
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: "build:next" exited with 1.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

./src/builder/posts.tsでエラーが生じており、posts.jsonを生成することができませんでした。
何度も申し訳ありません。

うーたんうーたん

ありがとうございます。動作しました。対応していただきありがとうございました。

1