skip to Main Content

Have been googling forever and found a way to change the <title>. That way is this: https://github.com/zeit/next.js/tree/master/examples/layout-component

The main problem with this is that everytime someone refresh the site/change page the title goes from http://localhost:3000 to the actual Title (eg. About us) and I’m a bit afraid of how this is affecting the SEO.

What is the correct way of chaning the page title dynamically?

My layout file:

import Link from 'next/link'
import Head from './../node_modules/next/head'

export default function Layout({ children, title = 'Welcome to my website' }) {
  return (
    <div>
        <Head>
          <title>{title}</title>
        </Head>

        {children}
    </div>
  )
}

4

Answers


  1. Chosen as BEST ANSWER

    I reninstalled "next" and "next-routes" in my dependencies and now this works.


  2. Check out next-seo and install it in your next.js application.

    yarn add next-seo 
    # or 
    npm install --save next-seo
    

    And it will handle the page title and the meta description for you magically.

    import React from 'react';
    import { NextSeo } from 'next-seo'; // then add the `NextSeo` at any `pages/` that you wish
    
    export default () => (
      <>
        <NextSeo
          title="About Us, or just any title that you wish"
          description="Then with a short description here."
        />
        <p>Simple Usage</p>
      </>
    );
    

    I have implemented the same tactic on my own web app here.

    Login or Signup to reply.
  3. If you need a dynamic title/description, for example for the route parameters case, you can do this. (Consider that the page name is [id].js)

    import React from 'react'
    import { NextSeo } from 'next-seo' //as proposed by @xun
    // import Head from "next/head" //alternative solution
    
    const Detail = ({id}) => {
      
      const title = `My ${id} title.`
      const description = `My ${id} description.`
      
      return (
         <>
         <NextSeo
          title={title}
          description={description}
        />
        <p>It works!</p>
        </>
        )}
    
    export default Detail
    

    And at the end of your file:

    export async function getServerSideProps({query}) {
      const { id } = query
    
      return {
        props: {
          id
        },
      };
    }
    

    Good luck!

    Login or Signup to reply.
  4. Well for me this works,

    Import <Head> from next,

    import Head from 'next/head'
    

    And in return statement,

        <>
          <Head>
            <title>Page Title</title>
          </Head>
          <section>
              <Your_JSX_CODE>
          </section>
        </>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search