1

I would like to fetch data always server side (in order to prevent them can be read from network tab)

When the page is refreshed (or first time loaded) process.server returns true and nothing can be seen on network tab.

  async asyncData({ params, $axios }) {
    console.log(process.server)
    const { id } = params;
    const url = `api/post/${params.id}`
    const post = await $axios.$get(url);
    return { post };
  }

However when I tried to navigate via internal link by using router-link or nuxt-link always end up with client side fetch. process.server returns false and request/response can be seen on network tab.

The only solution that I came up with using <a> instead internal links, thanks to this page is loaded and we can fetch server side.

Nuxt docs says always use nuxt-link instead <a> for the internal links but <a> can be used for external links. So I was wondering what the downside(s) is if we use for internal links (just in order to refresh page and make sure fetching on server side)

Or is there any better way to fetch always server side when we navigate?

Caner Sezgin
  • 328
  • 3
  • 16

1 Answers1

1

This is how I handle it and use nuxt-link's throughout.

Use the fetch hook then it's called on both.

async fetch() {
  this.getItems()
},

Additionally, if you wanted you can directly call serverside code through this.$root.context.ssrContext, which would be the same kind of thing you do if you use nuxtServerInit in stores.

async fetch() {
  if (process.server) {
    let items = []
    if (this.isset(this.$root, 'context.ssrContext.req.thingsModel')) {
      items = this.$root.context.ssrContext.req.cache.get('things', [])
      if (!items.length) {
        items = await this.$root.context.ssrContext.req.thingsModel.get(
          this.limit
        )
        items = this.$copy(items)
        this.$root.context.ssrContext.req.cache.put('things', items, 60000 * 60)
      }
    }

    this.items = items
  } else {
    this.getItems() // would be an ajax call to populate items
  }
},
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106