Categories
Nuxt.js

Nuxt.js — Error Pages, Async, and Request Data

Nuxt.js is an app framework that’s based on Vue.js.

We can use it to create server-side rendered apps and static sites.

In this article, we’ll look at how to add error pages, get async data, and get request data with Nuxt.js.

Error Page

We can add an error page to our Nuxt app by putting pages files in the layouts folder.

For example, if we want to show a page when we get a 404 error, we add a layouts/error.js file:

<template>
  <div>
    <h1 v-if="error.statusCode === 404">Page not found</h1>
  </div>
</template>

<script>
export default {
  props: ["error"],
};
</script>

It takes an error prop and we can check the statusCode property for the error status code.

Pages

Pages have special attributes and functions to make the development of our universal app.

For example, our pages may look like:

<template>
  <div>hello {{ name }}</div>
</template>

<script>
export default {
  asyncData(context) {
    return { name: "world" };
  },
  fetch() {
    //...
  },
  head() {
    return { foo: "bar" };
  },
};
</script>

The asyncData method lets us set the state before loading the component.

The returned object will be merged with our data object.

The fetch method lets us fill the store before rendering the page.

head lets us set the meta tags for the page.

loading prevents a page from automatically calling this.$nuxt.$loading.finish() as we enter it and this.$nuxt.$loading.start() as we leave it.

This lets us manually control the behavior.

transition defines a specific transition for the page.

scrollToTop is a boolean that specifies if we want to scroll to the top before rendering the page.

validate is a validator function for dynamic routes.

middleware defines the middleware for the page.

Async Data

We can use the asyncData method for getting data.

If we use Axios interceptors in our code, then we have to create an instance of it first.

For example, we can write:

import axios from 'axios'
const myAxios = axios.create({
  // ...
})
myAxios.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    // ...
  }
)

In our asyncData method, we can return a promise with it.

For example, we can write:

<template>
  <div>{{ title }}</div>
</template>

<script>
import axios from "axios";

export default {
  async asyncData({ params }) {
    const { data } = await axios.get(
      `https://jsonplaceholder.typicode.com/posts/${params.id}`
    );
    return { title: data.title };
  },
};
</script>

We have the asyncData method that takes an object with the params property.

It has the URL parameters for our page.

Then we can use axios to get the data we want and return the resolved value.

The resolved object can be retrieved from our component.

The Context

The context parameter for asyncData also has the req and res properties.

req has the request object.

And res has the response.

We use the process.server to check if the page is server-side rendered before using the request data.

To do that, we write:

pages/hello.vue

<template>
  <div class="container">{{host}}</div>
</template>

<script>
export default {
  async asyncData({ req, res }) {
    if (process.server) {
      return { host: req.headers.host };
    }
    return {};
  },
};
</script>

If process.server is true , then we can use the req object to get the request data.

Conclusion

We can get request data with Nuxt in our pages.

Also, we can create our own error page.

And we can initial our page with async data.

Categories
Nuxt.js

Nuxt.js — Error Handling and Plugins

Nuxt.js is an app framework that’s based on Vue.js.

We can use it to create server-side rendered apps and static sites.

In this article, we’ll look at how to handle async data errors and plugins with Nuxt.js.

Handling Errors

We can handle errors in our pages when we get async data.

To do that, we write:

<template>
  <div>{{ title }}</div>
</template>

<script>
import axios from "axios";

export default {
  async asyncData({ params, error }) {
    try {
      const { data } = await axios.get(
        `https://jsonplaceholder.typicode.com/posts/${params.id}`
      );
      return { title: data.title };
    } catch {
      error({ statusCode: 404, message: "Post not found" });
    }
  },
};
</script>

We have an asyncData method with an object that has the error property.

error is a function that we can to render the error.

Assets

Nuxt uses vue-loader, file-loader, and url-loader Webpack loaders for asset serving.

Also, we can use the static folder for static assets.

To add assets, we can write:

<template>
  <div class="container">
    <img src="~/assets/kitten.jpg" />
  </div>
</template>

<script>
export default {};
</script>

The ~ is a shorthand for the Nuxt root folder.

Static

We can also serve assets from the static folder.

For example, we can move our file to the static folder and write:

<template>
  <div class="container">
    <img src="/kitten.jpg" />
  </div>
</template>

<script>
export default {};
</script>

The / is the static folder’s shorthand.

Plugins

We can add plugins into our app.

They may come as external packages like Axios.

Or we can use Vue plugins.

To use Vue plugins, we have to add them manually.

For example, if we want to add a tooltip to our app, we install the v-tooltip package by running:

npm install --save v-tooltip

Then we create the plugins/vue-tooltip.js and add:

import Vue from 'vue'
import VTooltip from 'v-tooltip'

Vue.use(VTooltip)

Then in nuxt.config.js , we add:

plugins: [
  '@/plugins/vue-tooltip.js'
],

Then we can use it as usual by writing:

<template>
  <div class="container">
    <button v-tooltip="'hello world'">hello</button>
  </div>
</template>

<script>
export default {};
</script>

Inject in $root & context

We can also make functions available across all of our app.

To do that, we can call the inject function.

We can create our own plugin by adding plugins/hello.js :

export default (context, inject) => {
  const hello = msg => console.log(`hello ${msg}!`)
  inject('hello', hello)
}

Then we can add our plugin in nuxt.config.js :

plugins: [
  '@/plugins/hello.js'
],

Then we can call our hello function by writing:

<template>
  <div class="container"></div>
</template>

<script>
export default {
  mounted() {
    this.$hello("james");
  },
};
</script>

We also need:

context.$hello = hello

in the function we exported if we use Nuxt 2.12 or earlier.

We can also use the $hello function with the asyncData function by writing:

<template>
  <div class="container"></div>
</template>

<script>
export default {
  mounted() {
    this.$hello("james");
  },
  asyncData({ $hello }) {
    $hello("asyncData");
  },
};
</script>

The $hello is part of the context parameter of asyncData .

Conclusion

We can handle errors when we get data.

Also, we can create our own plugins and functions and inject them to our app.

Categories
Nuxt.js

Getting Started with Nuxt.js

Nuxt.js is an app framework that’s based on Vue.js.

We can use it to create server-side rendered apps and static sites.

In this article, we’ll look at how to get started with Nuxt.js.

Installation

We can create our Nuxt app with the create-nuxt-app program.

To do that, we run:

npx create-nuxt-app <project-name>

or:

yarn create nuxt-app <project-name>

Then we run:

npm run dev

to run our app.

Directory Structure

The directory structure for a Nuxt app follows some conventions.

The assets folder as static assets like styles, images, and fonts.

The layouts folder has the layout components for laying out contents on pages.

The middlewares folder has application middleware.

Middleware lets us define custom functions that can be run before rendering.

The pages folder has the views and routes.

It should only contain .vue files.

The folder can’t be renamed without changing our app’s configuration.

The plugins folder has the JavaScript plugins that we want to run before instantiating the root Vue instance.

The static folder serves static files directly to the public.

nuxt.config.js has the Nuxt.js custom configuration.

Routing

Nuxt does routing automatically by following the structure of the pages folder.

For instance, we can create the pages/hello.vue file:

<template>
  <div class="container">hello world</div>
</template>

<script>
export default {};
</script>

Then when we go to http://localhost:3000/hello, we see ‘hello world’ displayed.

If we want to accept URL parameters in our pages, we add a _ before the name of our file.

For example, we create a pages/users/_id.vue file and write:

<template>
  <div class="container">{{$route.params.id}}</div>
</template>

<script>
export default {};
</script>

We get the URL parameters from the $route.params object.

We can validate route params with the validate method.

To add it, we write:

<template>
  <div class="container">{{$route.params.id}}</div>
</template>

<script>
export default {
  validate({ params }) {
    return /^d+$/.test(params.id);
  },
};
</script>

We added the validate method with an object with the params property as the property.

Then we can return the condition for validation.

Also, we can add a _.vue file to handle URLs that don’t match any other URLs.

Named Views

We can use <nuxt name="top"/> or <nuxt-child name="top"/> in our layout or page to add the named views.

Views

The view defines the parts of our pages.

The default template for a Nuxt page is:

<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head {{ HEAD_ATTRS }}>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>

Default Layout

We can change the default layout by editing the layouts/default.vue file.

By default, it has:

<template>
  <div>
    <Nuxt />
  </div>
</template>

to render the page.

Custom Layout

Also, we can add custom layouts.

For example, we can create a layouts/blog.vue file and write:

<template>
  <div>
    <div>My blog</div>
    <Nuxt />
  </div>
</template>

to display a heading and the Nuxt component for displaying the page content.

Then to use the layout, we can create a file in the pages folder called pages/post.vue and add:

<template>
  <div>hello world</div>
</template>

<script>
export default {
  layout: "blog",
};
</script>

We set the layout property so that we can select the layout we want to use.

Now we should see the ‘My blog’ heading above ‘hello world’.

Conclusion

We can use Nuxt.js to create simple server-side rendered apps.

It’s based on Vue.js.

Categories
Next.js

Next.js — Dynamic Imports and Static Pages

We can create server-side rendered React apps and static sites easily Next.js.

In this article, we’ll take a look at dynamic imports and render static pages with Next.js.

Dynamic Import

ES2020 supports dynamic imports natively.

We can use this within our Next.js to dynamically import our components.

It also works with server-side rendering.

This lets us split our code into manageable chunks.

For example, we can write:

components/name.js

function Name() {
  return (
    <span>world</span>
  )
}

export default Name

pages/hello.js

import dynamic from 'next/dynamic'

const NameComponent = dynamic(() => import('../components/name'))

function Hello() {
  return (
    <div>hello <NameComponent /></div>
  )
}

export default Hello

We imported the dynamic function and passed in a callback that calls import to import the component.

Then we can use the NameComponent in our code.

Now we should see:

hello world

displayed.

Dynamic Component With Named Exports

We can create dynamic components with named exports.

To do that, we can write:

components/name.js

export function Name({ }) {
  return (
    <span>world</span>
  )
}

pages/hello.js

import dynamic from 'next/dynamic'

const NameComponent = dynamic(() => import('../components/Name').then((mod) => mod.Name)
)

function Hello() {
  return (
    <div>hello <NameComponent /></div>
  )
}

export default Hello

In the callback, we called import with the then callback to return the Name component from the module.

With Custom Loading Component

We can also add a component to show the component when the component loads.

For example, we can write:

components/name.js

function Name() {
  return (
    <span>world</span>
  )
}
export default Name

pages/hello.js

import dynamic from 'next/dynamic'

const NameComponent = dynamic(() => import('../components/Name'), { loading: () => <p>loading</p> })

function Hello() {
  return (
    <div>hello <NameComponent /></div>
  )
}

export default Hello

We have an object with the loading property in the code with a component as the value.

Disable Server-Side Rendering

Server-side rendering can be disabled by passing in an object into the dynamic function with the ssr property set to false .

For example, we can write:

components/name.js

function Name() {
  return (
    <span>world</span>
  )
}
export default Name

pages/hello.js

import dynamic from 'next/dynamic'

const NameComponent = dynamic(() => import('../components/Name'), { ssr: false }
)

function Hello() {
  return (
    <div>hello <NameComponent /></div>
  )
}

export default Hello

Static HTML Export

We can export our app to static HTML with the next export command.

It works by prerendering all the pages to HTML.

The pages can export a getStaticPaths property that returns all the paths that we want to prerender.

next export should be used when there are no dynamic data changes in our app.

To use it, we run:

next build && next export

next build builds the app and next export gets us the HTML pages.

We can also add both commands to our package.json file:

"scripts": {
  "build": "next build && next export"
}

and run npm run build to run it.

getInitialProps can’t be used with getStaticProps or getStaticPaths on any page.

Conclusion

We can dynamically import components with Next.js.

Also, we can build our Next.js app to static HTML files.

Categories
Next.js

Next.js — Middlewares and Preview Mode

We can create server-side rendered React apps and static sites easily Next.js.

In this article, we’ll take a look at route middlewares and preview mode with Next.js.

Connect/Express Middleware Support

We can use Connect compatible middleware.

For example, we can add the cors middleware by installing it and adding to our Next.js app.

To install it, we run:

npm i cors

or

yarn add cors

Then we can add it to our API route by writing:

import Cors from 'cors'

const cors = Cors({
  methods: ['GET', 'HEAD'],
})

function runMiddleware(req, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result)
      }
      return resolve(result)
    })
  })
}

async function handler(req, res) {
  await runMiddleware(req, res, cors)
  res.json({ message: 'hello world' })
}

export default handler

We imported the Cors function.

Then we use it to create the cors middleware.

We can specify the request methods that can be used with the route.

The runMiddleware function runs the middleware by calling the fn middleware function and then resolve to the result if it’s successful.

Otherwise, the promise is rejected.

The handler is the route handler that runs the middleware and then returns the response.

Response Helpers

Next.js comes with various response helpers.

The res.status(code) method lets us set the status code of the response.

code is an HTTP status code.

res.json(json) method lets us send a JSON response.

json is a valid JSON object.

res.send(body) lets us send an HTTP response, where body is a string, object, or buffer.

res.redirect takes an optional status and path to let us redirects to a specific path or URL.

The default value of status is 307.

For example, we can call them by writing:

export default (req, res) => {
  res.status(200).json({ name: 'hello' })
}

They can be chained together.

Preview Mode

We can preview routes that are statically generated.

Next.js has a preview mode feature to solve the problem.

It’ll render the pages at request time instead of build time and fetch the draft content instead of the published content.

To use it, we call the res.setPreviewData method to do the preview.

For example, we can write:

export default (req, res) => {
  res.setPreviewData({})
  res.end('Preview mode')
}

to enable it.

Securely Accessing Data

We can access data by writing from the preview route and send to our page.

To do this, we create our preview API route by creating the pages/api/preview.js file:

export default async (req, res) => {
  const response = await fetch(`https://yesno.wtf/api`)
  const data = await response.json();
  res.setPreviewData(data)
  res.redirect('/post')
}

We get the data from an API and call setPreviewData so that we can get it from the getStaticProps function in our page JavaScript file.

Then we redirect to our file so that we can see the data on our page.

In pages/post.js , we write:

function Post({ data }) {
  return (
    <div>{data && data.answer}</div>
  )
}

export async function getStaticProps(context) {
  if (context.preview) {
    return {
      props: {
        data: context.previewData
      }
    }
  }
  return { props: { data: { answer: 'not preview' } } }
}

export default Post

We check is preview mode is on by checking the context.preview property.

If it’s true , then we get the preview data from context.previewData .

And then we display the data in our Post component.

Conclusion

We can add preview mode with Next.js so that we can view the output before it goes live.

Also, we can use Connect or Express middleware in our Next.js apps.