简体   繁体   中英

Next Js Custom Routes and SSR

I am using apollo with next and recently I noticed that custom routes breaks SSR. Usually if you navigate through pages apollo caches the query and when you are on the page the next time, it serves everything from cache. However with custom routes, the cache is never used.

I also noticed that when I click on these pages, an error flashes in the console. But it goes away very fast and I wasn't able to copy it here.

Server.js

// 
   server.get('/about-us', (req, res) => app.render(req, res, '/about'));


   server.get('/about', (req, res) => res.redirect(301, '/about-us'));

Menu Click Handler

const navigate = link => () => {
        Router.push(link);
    };

Menu Items

export const menu = [
    {
        name: 'Home',
        url: '/',
    },
    {
        name: 'Catalogs',
        url: '/catalogs',
    },
    {
        name: 'Shop',
        url: '/shop',
    },
    {
        name: 'Wholesale',
        url: '/wholesale',
    },
    {
        name: 'About Us',
        url: '/about-us',
        prefetch: true,
    },
    {
        name: 'Contact Us',
        url: '/contact-us',
        prefetch: true,
    },
];

Based on a suggestion from nextjs spectrum I tried prefetching custom pages in the TopNav Component but it didn't work.

const prefetch = url => {
        if (process.browser) {
            console.log('prefetching these urls', url);
            Router.prefetch(url);
        }
    };

    useEffect(() => {
        menu.forEach(menuItem => {
            if (menuItem.prefetch) {
                prefetch(menuItem.url);
            }
        });
    }, []);

I was able to figure out the problem. This is not really well documented but you need to prefetch the component. So for my case instead of prefetching /about-us I should have prefetched /about .

That's why there is as prop in the link component. Nextjs 9 just got released which fixes this issue.

https://nextjs.org/blog/next-9#dynamic-route-segments

For nextjs 9 you can save your file as [pid].js and it will catch all paths in a specific route. ie for /products/test-product you have to create folder products and inside that add [pid].js .

I needed to query for product based on slug so I added this and voila, I have access to the slug inside my component.

Product.getInitialProps = async ({ query }) => {
    return { slug: query.pid };
};

These issues were pretty frustrating before next 9 but it's heavily simplified and it helped me fully remove server.js .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM