If you are an avid reader, you might have a News Aggregator app installed on your device. Wouldn't it be awesome to create your own News Aggregator app that you can control and customize according to your needs?
This is what you'll be doing today by creating a News Aggregator app using Strapi and Nuxt.js.
Strapi is a headless CMS (Content Management System) based on Node.js and builds APIs. Strapi provides a UI where you can develop your collection types and subsequent APIs to fetch the data from Strapi using REST or GraphQL API. The best thing about Strapi is that it is completely open-source and self-hosted.
Nuxt.js is a framework for building Vue.js apps that are universal. It means the code written in Nuxt.js can run on both client and server, offering Client Side Rendering and Server Side Rendering simultaneously.
This tutorial aims to learn about Strapi and Nuxt.js by building a News Aggregator app with Strapi and Nuxt.js. In this app, you'll:
The source code for this project is available on GitHub: https://github.com/ravgeetdhillon/strapi-nuxtjs-news-app.
Here is what you’ll need to get started.
Prerequisites
The entire source code for this tutorial is available in this GitHub repository.
Setting Up Project You'll need a master directory that holds the code for both the frontend (Nuxt.js) and backend (Strapi). Open your terminal, navigate to a path of your choice, and create a project directory by running the following command:
mkdir strapi-nuxtjs-news-app
In the strapi-nuxtjs-news-app
directory, you’ll install both Strapi and Nuxt.js projects.
In your terminal, execute the following command to create the Strapi project:
npx create-strapi-app backend --quickstart
This command will create a Strapi project with quickstart settings in the backend directory. Once the execution completes for the above command, your Strapi project will start on port 1337 and open up localhost:1337/admin/auth/register-admin in your browser. At this point, set up your administrative user:
Enter your details and click the Let's Start button, and you'll be taken to the Strapi dashboard.
Creating Feed Sources Collection Type
Under the Plugins header in the left sidebar, click the Content-Types Builder tab and then click Create new collection type to create a new Strapi collection.
Create a new collection type with Display name - feedsources and click Continue in the modal that appears.
Next, create two fields for this collection type:
Once you have added all these fields, click the Finish button and save your collection type by clicking the Save button.
Creating News Items Collection Type
In the same way, as you created the Feedsources collection type, create a collection type for storing news items.
In the modal that appears, create a new collection type with Display name - newsitems and click Continue.
Next, create the following fields for your collection type:
Once you have added all these fields, click the Finish button and save your collection type by clicking the Save button.
Creating Subscribers Collection Type
Finally, you need to create a collection type for registering subscribers. Create a new collection type with Display name - subscribers and click Continue in the modal that appears.
For the Subscribers Collection type, add the following field to your collection type:
Once you have added this field, click the Finish button and save your collection type by clicking the Save button.
At this point, all of your collection types are set up, and the next thing you need to do is add some data to the Feedsources collection type.
You can add RSS feed URLs according to your choice, but to follow along with this tutorial, add the following URLs and enable them as well:
At this point, you have enough data in your Feedsources collection type to fetch the news items from these feeds.
To automate the fetching of news items from the feed URLs, you can take advantage of CRON jobs in Strapi, which allows you to run tasks regularly or at a particular time. For this app, it would be better to check for the new news items and then add them to the Newsitems collection type every day at a specific time.
You can use the RSS-parser NPM package to parse the RSS feeds and get the metadata about the items from the blog. To install this package, open your terminal and run the following commands:
1 cd backend
2 npm install rss-parser --save
Next, you need to write a script to fetch the news items from the feeds and add them to the Newsitems
collection type.
In the config
directory, create a feedUpdater.js
file and add the following code to it:
1 'use strict';
2
3 const Parser = require('rss-parser');
4
5 // 1
6 function diffInDays(date1, date2) {
7 const difference = Math.floor(date1) - Math.floor(date2);
8 return Math.floor(difference / 60 / 60 / 24);
9 }
10
11 // 2
12 async function getNewFeedItemsFrom(feedUrl) {
13 const parser = new Parser();
14 const rss = await parser.parseURL(feedUrl);
15 const todaysDate = new Date().getTime() / 1000;
16 return rss.items.filter((item) => {
17 const blogPublishedDate = new Date(item.pubDate).getTime() / 1000;
18 return diffInDays(todaysDate, blogPublishedDate) === 0;
19 });
20 }
21
22 // 3
23 async function getFeedUrls() {
24 return await strapi.services.feedsources.find({
25 enabled: true,
26 });
27 }
28
29 // 4
30 async function getNewFeedItems() {
31 let allNewFeedItems = [];
32
33 const feeds = await getFeedUrls();
34
35 for (let i = 0; i < feeds.length; i++) {
36 const { link } = feeds[i];
37 const feedItems = await getNewFeedItemsFrom(link);
38 allNewFeedItems = [...allNewFeedItems, ...feedItems];
39 }
40
41 return allNewFeedItems;
42 }
43
44 // 5
45 async function main() {
46 const feedItems = await getNewFeedItems();
47
48 for (let i = 0; i < feedItems.length; i++) {
49 const item = feedItems[i];
50
51 const newsItem = {
52 title: item.title,
53 preview: item.contentSnippet,
54 link: item.link,
55 creator: item.creator,
56 sponsored: false,
57 };
58
59 await strapi.services.newsitems.create(newsItem);
60 }
61 }
62
63 // 6
64 module.exports = {
65 main,
66 };
In the above code:
diffInDays
function to calculate the number of days between the two given dates. This function is used in the getNewFeedItemsFrom
function.getNewFeedItemsFrom
function, you parse the feed (feedUrl
) using the RSS-parser
NPM package. Then you filter out the feed items that were created in the last 24 hours (diffInDays === 0
).getFeedUrls
function, you use the Strapi service (strapi.services
) to get (find
) all the enabled ({enabled: true}
) feed URLs from the Feed Sources (feedsources
) collection type.getNewFeedItems
function calls the getFeedURLs
to get feed URLs then and loops over the feed URLs array (feeds
) to fetch the new feed items (feedItems
) using the getNewFeedItemsFrom
function. Finally, the function returns all the new feed items (allNewFeedItems
).feeditems
array (feedItems) and construct a newsItem
object used to create a new news item in the NewItems Collection type.main
function is exported by the feedUpdater.js
fileIt is a good idea to export all of your tasks from a single file. So, create a tasks.js
file in the config
directory and add the following code to it:
1 'use strict';
2
3 async function updateFeed() {
4 return await strapi.config.feedUpdater.main();
5 }
6
7 module.exports = {
8 updateFeed,
9 };
In the functions
directory, update the cron.js
file by adding the following code to it:
1 'use strict';
2
3 module.exports = {
4 // 1
5 '* * * * *': {
6 // 2
7 task: async () => {
8 await strapi.config.tasks.updateFeed();
9 },
10 // 3
11 options: {
12 tz: 'Asia/Kolkata',
13 },
14 },
15 };
In the above code:
* * * *
) to define when the specified task
needs to be run. In this case, it will run every minute. But this setting is only for testing purposes. Once you have verified that the CRON job works successfully, replace the * * * * *
with 0 12 * * *
, which makes the CRON job run at 12:00 every day following the time zone specified. For more info about CRON syntax, you can try https://crontab.guru/.task
key is provided with the updateFeed
function.options.tz
is used to specify the time zone for the CRON job to run in.Finally, to enable the CRON jobs in Strapi, add the following config settings in the config/server.js
file:
1 module.exports = ({ env }) => ({
2 ...
3 cron: {
4 enabled: true,
5 },
6 })
At this point, shut down the Strapi development server by pressing Control-C and restart it by running the following command:
npm run develop
Wait for a minute, and you'll see that the CRON job will execute and update the Newsitems collection type:
Once you are happy with the result, shut down the Strapi development server and change the replace the * * * * *
with 0 12 * * *
in the functions/cron.js
file.
At this point, you have enough data in your Strapi CMS to test the API. Open Postman and send a GET request to the Newsitems API endpoint - localhost:1337/newsitems. You will not be able to access the endpoint as you have not allowed public access to it.
Since you want to allow public access to your Newsitems
collection type, so you need to configure the permissions related to the Public role. So to configure the permissions for your news items endpoint, click on the Settings tab under the General header and select Roles under the Users & Permissions Plugin. Click the Edit icon to the right of the Public Role.
Scroll down to find the Permissions tab and check the find and findone permissions for the Newsitems collection type. For the Subscribers collection type, check the create permission to allow users to signup as subscribers. Once done, save the updated permissions by clicking the Save button.
Go back to Postman, send a GET request to the localhost:1337/newsitems, and you'll get the list of news items from the Strapi.
Next, send a GET request to, for example, localhost:1337/newsitems/7, to fetch an individual news item from the Strapi, and you'll get the individual news item with ID 7 as a response from the Strapi.
That's it for the Strapi part of the project. Next, you need to set up a Nuxt.js app and connect it with the Strapi backend.
Now that you have completely set up your Strapi project, it's time to build the Nuxt.js frontend app.
Since your current terminal window is serving the Strapi project, open another terminal window and execute the following command from the project's root directory (strapi-nuxtjs-news-app
) to create a Nuxt.js project:
npx create-nuxt-app frontend
On the terminal, you'll be asked some questions about your Nuxt.js project. For this tutorial, choose the options highlighted below:
Once you have answered all the questions, it will install all the dependencies.
After the installation is complete, navigate into the frontend
directory and start the Nuxt.js development server by running the following commands:
1 cd frontend
2 npm run dev
This will start the development server on port 3000 and take you to localhost:3000. The first view of the Nuxt.js website will look like this:
Installing @nuxtjs/strapi Module @nuxt/strapi is the Nuxt module for integrating Strapi with Nuxt.js.
Shut down the Nuxt.js development server by pressing Control-C in your terminal and execute the following command to install the module for your Nuxt.js app:
npm install @nuxtjs/strapi --save
Once the installation is complete, open the nuxt.config.js
file and add the following properties to the default object exported by nuxt.config.js
:
1 export default {
2 ...
3
4 // 1
5 modules: [
6 ...
7 '@nuxtjs/strapi',
8 ],
9
10 // 2
11 strapi: {
12 url: '<http://localhost:1337>',
13 entities: ['newsitems', 'subscribers'],
14 },
15 }
In the above config:
@nuxtjs/strapi
module to the modules
array so that Nuxt.js loads this package whenever the Nuxt.js app is initialized.strapi
config variable. url
corresponds to the URL of the Strapi server. In the entities
array, you can specify the collection types present in your API. This will help you to access them using the $strapi
object, for example - $strapi.$newsitems
. For more options, you can refer to this official documentation.Designing a Layout Page Before you start designing the core pages of the app, you can create a default layout that contains the styles that are applied to all the pages using the default layout.
At the root of the Nuxt.js project (frontend
), create a layouts
directory. Then in the layouts
directory, create a default.vue
file and add the following code to it:
1 <template>
2 <Nuxt />
3 </template>
4
5 <style>
6 html,
7 body {
8 font-family: 'Inter';
9 }
10
11 .one-liner {
12 text-overflow: ellipsis;
13 overflow: hidden;
14 white-space: nowrap;
15 }
16 </style>
In the above layout, you have defined the Inter font for your Nuxt.js app and created a .one-liner
CSS class which you'll be using later in the core pages to restrict the multiline paragraph to a single line for better UI across the app.
Now that you have set up the necessary packages for developing your Nuxt.js website, you need to design the news pages.
Designing All News Page
This page will fetch all of your news items from Strapi CMS and display them in the UI.
In the pages
directory, open the index.vue
file and replace all the existing code with the following code:
1 <template>
2 <section class="py-5">
3 <b-container>
4 <b-row>
5 <b-col lg="7">
6 <!-- 3 -->
7 <div v-if="!newsItems">Loading...</div>
8 <!-- 4 -->
9 <div v-else>
10 <h1 class="mb-5 border-bottom">News</h1>
11 <nuxt-link to="/search">Search</nuxt-link>
12 <br /><br />
13 <div
14 v-for="(newsItem, index) in newsItems"
15 :key="index"
16 class="mb-5"
17 >
18 <news-item :item="newsItem"></news-item>
19 </div>
20 </div>
21 </b-col>
22 </b-row>
23 </b-container>
24 </section>
25 </template>
26
27 <script>
28 export default {
29 layout: 'default',
30 data() {
31 return {
32 // 1
33 newsItems: null,
34 };
35 },
36 // 2
37 async created() {
38 this.newsItems = await this.$strapi.$newsitems.find();
39 },
40 };
41 </script>
In the above code:
newsItems
as null
in the data
object which is passed to the <template>
.created
lifecycle hook, you fetch (find()
) all the news items ($newsitems
) from the Strapi ($strapi
) and assign the response to the newsItems
data variable.<template>
, you check if the newsItems
variable is Falsy, then you render a Loading...
message.newsItems
variable evaluates to a Truthy, you loop (v-for
) over it and render the news-item
component by passing the current newsItem
to the item
prop.In the components
directory, create a new file, NewsItem.vue
and add the following code to it:
1 <template>
2 <div>
3 <b-badge v-if="item.sponsored" variant="info" class="mb-2">
4 Sponsored
5 </b-badge>
6 <nuxt-link :to="`/newsitems/${item.id}`" class="text-dark">
7 <h2 class="h4">{{ item.title }}</h2>
8 </nuxt-link>
9 <p
10 class="mb-1 one-liner text-muted"
11 v-html="sanitizeHtml(item.preview)"
12 ></p>
13 </div>
14 </template>
15
16 <script>
17 export default {
18 props: {
19 item: {
20 type: Object,
21 default: () => ({}),
22 },
23 },
24 };
25 </script>
Since you will parse the HTML from external sources, it makes your app vulnerable to XSS attacks. You first need to sanitize the HTML and then pass it to the v-HTML
prop to mitigate this problem.
You can use the DOMPurify library to sanitize the HTML and prevent XSS attacks. In your terminal, run the following command to install this package:
npm install dompurify --save
Sanitization is used across various places in an app. So to respect the DRY (Don't Repeat Yourself) principle, it is often a good idea to create mixins to make these functions available across your app without having to write the same code again and again.
In the plugins
directory, create an index.js
file and add the following code to it:
1 import Vue from 'vue';
2 import DOMPurify from 'dompurify';
3
4 Vue.mixin({
5 methods: {
6 sanitizeHtml(value) {
7 return DOMPurify.sanitize(value);
8 },
9 },
10 });
Add the above plugin to the plugins
array in the nuxt.config.js
file as it allows the Nuxt.js to execute these plugins before rendering a page as in the code below:
1 export default {
2 ...
3 plugins: ['~/plugins/index.js'],
4 };
At this point, save your progress and start your Nuxt.js development server by running:
npm run dev
Visit localhost:3000 and you’ll see your news page rendered by Nuxt.js:
Designing a Single News Item Page The next step is to design a single news item page that needs to be dynamic. You can fetch a single news item from endpoint - localhost:1337/newsitems/:id.
In the pages
directory, create a sub-directory, newsitems
. Then in the newsitems
directory, create a _id.vue
file and add the following code to it:
1 <template>
2 <section class="py-5">
3 <b-container>
4 <b-row>
5 <b-col lg="7" class="mx-lg-auto">
6 <!-- 3 -->
7 <div v-if="!newsItem">Loading...</div>
8 <!-- 4 -->
9 <div v-else>
10 <nuxt-link to="/">Back</nuxt-link>
11 <br /><br />
12 <b-alert v-if="newsItem.sponsored" variant="info" show>
13 This is a Sponsored post.
14 </b-alert>
15 <h1 class="mb-4">{{ newsItem.title }}</h1>
16 <div class="small mb-4">
17 <span v-if="newsItem.creator.trim().length > 0">
18 Written by <b>{{ newsItem.creator }}</b>
19 <br />
20 </span>
21 <span>
22 Published on
23 {{ new Date(newsItem.published_at).toLocaleDateString() }}
24 </span>
25 </div>
26 <p v-html="sanitizeHtml(newsItem.preview)"></p>
27 <a :href="newsItem.link" target="_blank">
28 Read on Original Blog
29 <!-- 5 -->
30 <ExternalIcon />
31 </a>
32 </div>
33 </b-col>
34 </b-row>
35 </b-container>
36 </section>
37 </template>
38
39 <script>
40 export default {
41 layout: 'default',
42 data() {
43 return {
44 // 1
45 newsItem: null,
46 };
47 },
48 // 2
49 async created() {
50 const { id } = this.$route.params;
51 this.newsItem = await this.$strapi.$newsitems.findOne(id);
52 },
53 };
54 </script>
In the above code:
newsItem
as null
in the data
object which is passed to the <template>
.created
lifecycle hook, first, you destructure the id
of the dynamic route from this.$route.params
object. Then, you use the $strapi
object to fetch (findOne()
) the news item with id (id
) and assign the response to the newsItem
data variable.<template>
, you check if the newsItem
variable is Falsy, then you render a Loading...
message.newsItem
variable evaluates to a Truthy, you use Vue template variables to render the UI for it.<ExternalIcon />
component so next, you need to create one.In the components
directory, create an ExternalIcon.vue
file and add the following code to it:
1 <template>
2 <svg width="12px" height="12px" viewBox="0 0 24 24">
3 <g
4 stroke-width="2.1"
5 stroke="currentColor"
6 fill="none"
7 stroke-linecap="round"
8 stroke-linejoin="round"
9 >
10 <polyline points="17 13.5 17 19.5 5 19.5 5 7.5 11 7.5"></polyline>
11 <path d="M14,4.5 L20,4.5 L20,10.5 M20,4.5 L11,13.5"></path>
12 </g>
13 </svg>
14 </template>
Save your progress and wait for the server to Hot Reload. Click on any news item on the index page to open the single news item page and the page will render as follows:
In the pages
directory, create a search.vue
file and add the following code to it:
1 <template>
2 <section class="py-5">
3 <b-container>
4 <b-row>
5 <b-col lg="7" class="mx-lg-auto">
6 <nuxt-link to="/">Back</nuxt-link>
7 <br /><br />
8 <h1 class="mb-5 border-bottom">Search News</h1>
9 <div class="d-flex mb-5">
10 <!-- 3 -->
11 <b-form-input
12 v-model="searchQuery"
13 type="search"
14 placeholder="Search"
15 class="mr-3"
16 ></b-form-input>
17 <!-- 4 -->
18 <b-btn @click="searchItems">Search</b-btn>
19 </div>
20 <div v-if="!newsItems">Nothing Found</div>
21 <div
22 v-for="(newsItem, index) in newsItems"
23 v-else
24 :key="index"
25 class="mb-5"
26 >
27 <news-item :item="newsItem"></news-item>
28 </div>
29 </b-col>
30 </b-row>
31 </b-container>
32 </section>
33 </template>
34
35 <script>
36 export default {
37 layout: 'default',
38 // 1
39 data() {
40 return {
41 newsItems: null,
42 searchQuery: null,
43 };
44 },
45 // 2
46 methods: {
47 async searchItems() {
48 this.newsItems = await this.$strapi.$newsitems.find({
49 _q: this.searchQuery,
50 });
51 },
52 },
53 };
54 </script>
In the above code:
newsItems
and searchQuery
as null
in the data
object which is passed to the <template>
.searchItems()
method which is used to search the NewsItems ($strapi.$newsitems
) collection type by providing the searchQuery
data variable as the query parameter (_q
).b-form-input
) is bound to the searchQuery
data variable using the v-model
.b-btn
) that runs the searchItems
function on button click (@click
).Save your progress and wait for the server to Hot Reload. Go to the localhost:3000/search and try searching for a news item:
The final step to complete your News Aggregator app is to allow users to signup as subscribers.
In the components
directory, create a SubscribeBox.vue
file and add the following code to it:
1 <template>
2 <div class="bg-light">
3 <div class="p-3">
4 <p class="lead font-weight-normal mb-0">Subscribe to our newsletter</p>
5 <p class="text-muted">
6 Get daily updates about things happening in the world of tech and
7 business.
8 </p>
9 <div class="d-flex flex-column">
10 <!-- 3 -->
11 <b-form-input
12 v-model="email"
13 type="email"
14 placeholder="Your Email"
15 class="mb-2"
16 ></b-form-input>
17 <!-- 4 -->
18 <b-btn @click="addSubscriber">Subscribe</b-btn>
19 <!-- 5 -->
20 <p v-if="message" class="mt-3 mb-0">{{ message }}</p>
21 </div>
22 </div>
23 </div>
24 </template>
25
26 <script>
27 export default {
28 // 1
29 data() {
30 return {
31 email: null,
32 message: null,
33 };
34 },
35 // 2
36 methods: {
37 async addSubscriber() {
38 const response = await this.$strapi.$subscribers.create({
39 email: this.email,
40 });
41 if (response) {
42 this.message = 'Thanks for subscribing!';
43 }
44 },
45 },
46 };
47 </script>
In the above code:
email
and message
as null
in the data
object which is passed to the <template>
.addSubscriber
method which is used to create (create({email: this.email})
) a new subscriber in Subscribers Collection type ($strapi.$subscribers
).email
data variable is bound to the Form Text input (b-form-input
) using the v-model
.b-btn
) that runs the searchItems
function on the button click (@click
).message
evaluates to a Truthy, you render the message telling the user that they have been successfully subscribed.At this moment SubscribeBox
is just a component, so you need to render it in a page. Open the pages/index.vue
file and update the <template>
by adding the following code:
1 <template>
2 <section class="py-5">
3 <b-container>
4 <b-row>
5 <b-col lg="7">
6 <!-- -->
7 </b-col>
8 <b-col lg="1"></b-col>
9 <b-col lg="4">
10 <SubscribeBox />
11 </b-col>
12 </b-row>
13 </b-container>
14 </section>
15 </template>
Save your progress and wait for the server to Hot Reload. Go to the localhost:3000 and the SubscribeBox
component will render as follows:
Test the Subscription form by adding a valid email and click Subscribe button. Once you get a thanks message, check out the Subscribers collection type in your Strapi CMS for the newly registered email:
That's it. Your app is complete and below is a complete overview of the app in action:
That's it! You have successfully set up a News Aggregator app using Nuxt.js as a frontend and Strapi as a backend. You learned about API Permissions in Strapi, CRON jobs in Strapi, implementing views in Nuxt.js, and more. The next step would be to deploy the app. You can deploy the Strapi CMS on DigitalOcean and the Nuxt.js app on Netlify.
The entire source code for this tutorial is available in this GitHub repository.