Create a catchall dynamic route in remix - reactjs

I'm using remix to serve my react application.
All my pages have dynamic slugs, therefore I need to find a way to resolve the following type of URL:
eg. mywebsite.com/dynamic_slug
If I create an $index.jsx file in the routes folder it works in that all the dynamic URLs resolve to that file, BUT, I can't seem to find a way to then read the slug in the compontent so that I serve the right data.
Many thanks to any responders.

You access the dynamic params via the params object passed to your loaders and actions.
// routes/$index.jsx
export async function loader({request, params, context}) {
const slug = params.index // whatever $name is
//...
}
https://remix.run/docs/en/v1/guides/data-loading#route-params

Related

In Next.js 13 app directory, how do I incrementally generate new pages?

I have multiple items from a CMS. /items/1 all the way to /items/9999. The content is immutable, so I don't have to worry about revalidateing them.
However, items do get added to the CMS frequently, maybe multiple times in a day. I want to make a static website. How can I add new static pages incrementally?
The CMS isn't handled by me, so there's no way I can add a hook.
As per the docs, by default, route segment parameters that were not statically generated at build-time by generateStaticParams function will be generated on demand. These non-generated segments will use Streaming Server Rendering. This is basically the equivalent to fallback: true on getStaticPaths function on pages folder page components.
Just make sure to perform the appropriate checks on your page component in case the requested data doesn't exist in the CMS. That way you can throw a Not Found error and render a 404 UI making use of the not-found.js file. Example from the docs:
import { notFound } from 'next/navigation';
export default async function Profile({ params }) {
const user = await fetchUser(params.id);
if (!user) {
notFound();
}
// ...
}

How add ability add query params for gatsby routes?

How to generate pages in gatsby that will allow you to add parameters to the routing like https://page1?someParam=param or https://page1/param
What I mean? When we navigate to page page1 in gatsby it work's fine, but what if I just want add uniq params for page for google analitics? so for this I want to have ability
add some additional params for the page from where I made redirect, but when I add
for page1 some params like https://page1?someParam=param or https://page1/param, it updated and show me just https://page1 instead.
I suppose that it's related to way how I created pages. Here is my code:
createPage({
path: `${localePrefix}/${slug}`, // so should I change it here in order to work as needed?
component: PageTemplate,
context: {
...context,
localizedPaths,
},
})
Can it be fixed with?
matchPath: path: ${localePrefix}/${slug}?*,
matchPath: path: ${localePrefix}/${slug}/*,
Recap:
My question is about why gatsby remove query params from pages?
https://some_site/some_page?some_param=323
translates into
https://some_site/some_page
https://page1?someParam=param or https://page1/param are not the same. While a query parameter (first case: ?someParam=param) is an optional value that doesn't change the rendered page (it doesn't point to any specific route hence it's not requesting any file). The second one (https://page1/param) is accessing a /pages/param route.
Since they are URL parameters, you don't need to change anything in your project, you just need to catch them using JavaScript. They are handled in thee:
const urlParams = new URLSearchParams(window?.location?.search);
Note: you can access directly location prop in Gatsby
If your project is replacing https://some_site/some_page?some_param=323 to https://some_site/some_page it's because some server-side configuration or a CDN, not because of Gatsby's behavior, like any other React project.

It is possible concatenate dynamic url in Next JS? [duplicate]

I've tried to check through the official documentation, various issues, and inside SO previous questions, but I can't find confirmation if it's possible to create a dynamic route in Next.js that contains a constant or a string combined with a slug. For example?
pages/
something-[slug].jsx
Is it possible or not? I'm inclined to think not because of the examples I've tried to build, but possibly I'm missing something.
While Next.js doesn't provide built-in support for partial dynamic routes (like something-[slug]), you can work around it by setting up an actual dynamic route and use rewrites to map the incoming URL (in the format you want) to that route.
For instance, you could setup a dynamic route under /pages/something/[slug].jsx, then configure a rewrites rule in next.config.js as follows.
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/something-:slug',
destination: '/something/:slug'
}
];
}
}

Next js multiple dynamic pages

I am using Next Js in my application. I know that we can create dynamic pages using pages folder, but i can not create a certain design for pages structure. What i want to achieve: I need to have the next paths in my application: /user/pageAccordingUserIdWhichIsDymamicPage/userDataWhichIsStaticPage/anotherDynamicPage. My question is, how the folder structure should look? Note: all paths are related to user, so i expect that the pages should be located in one page folder from pages.
This is possible using a feature known as dynamic routing. For more information see: https://nextjs.org/docs/routing/dynamic-routes.
Creating the Routes
For each dynamic route/url you wish to create follow the process below:
Divide the URL into different sections based on the '/' character.
For example: "/users/roger/data" would be split to [users, roger, data].
For each section of the URL, create a folder with the corresponding name. If a certain part of the URL is dynamic, the name of the folder should be wrapped in square brackets- [dynamicData].
Finally, create as many index.js files as you need. These files should be placed in the folders you created.
For example, if you wanted the page /users/roger to work - you would go to your pages directory, users, roger, and put an index.js file there. Remember - that if you want 'roger' to be dynamic, you would create a dynamic folder like [userName] instead of roger.
Retrieving the Data
You could then access the dynamic properties in each index.js file by acceding the router's query property. For example:
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const {userId, dynamic} = router.query
return <p>
userId: {userId} <br />
dynamic: {dynamic}
</p>
}
export default Post
You would obviously replace the {userId, dynamic} with the names you chose for the dynamic routes (i.e - the names of the folders).
(Example adapted from the link above)
In Next js your route endpoints are defined by the file name thus making it quick and easy to create a new route.
Now let's say that you want to create a route like this "/profile/:id"
with id being your custom parameter.
To create a file with a custom parameter just surround your custom parameter with brackets like this [id]
You can also use the three dot syntax (like this [...id]) to accept infinite unspecified dynamic pages.
I would suggest watching the video linked down below which really helped me get started with Next js.
nextjs crash course

2 levels nested routing in nextjs

I carefully read the docs of next routing system.
It only mentions that I could achieve dynamic routing like this:
http://localhost:3000/level1/dynamicSlug
But I am trying to achive something like this:
http://localhost:3000/level1/level2/dynamicSlug
And I want level2 to be created dynamic too
Thanks so much !
It is possible to do nested scenarios according to your request in this way.
for example:
pages/
level1/
[dynamicSlug]/
- index.js // will match for /level1/1234
level2/
- index.js // will match for /level1/level2
- [dynamicSlug].js // will match for /level1/level2/1234
Or
pages/
level1/
[dynamicSlug]/
- index.js // will match for /level1/1234
level2/
- index.js // will match for /level1/level2
[dynamicSlug]/
- index.js // will match for /level1/level2/1234
You have 2 choices:
Using v9 Dynamic Routing by calling the folder as [dynSlag] and putting your page file inside.
Using custom server and routing, you will need to define a custom server, map your path to a specific next page.
I know this is a bit of an old post, but I'd just like to share my working response with NextJS v11.
I want dynamic routing at two levels. E.g.:
{siteroot}/dynamicPage
{siteroot}/dynamicUrlSection/dynamicPage
My folder structure is:
/pages/[section]/[page].tsx
/pages/[section]/index.tsx
This way, the "dynamicPage" path at the root is handled by index.tsx, and nested routes are handled by [page].tsx
BONUS INFO: I am working with Contentful as a CMS. I use a single content model for all the pages at both levels.
The model has "section" and "page" properties.
The entries that serve the root dynamic pages (i.e. /pages/[section]/index) have a compound value in the "page" property of {section}-index. I then have to be a bit smart in my client code:
if (!page) {
page = `${section}-index`;
}
await fetchData(section, page);
Using the example right from the NextJs documentation, I use this hack, maybe you could use it.
<Link href="/posts/[id]" as={`/posts/${subFolder}${id}`}>
"as" will have a value like /posts/nested_subfolder_file.md
And in the getPostData function, just do this little change:
const nestedPaths = id.split('_')
const fileName = `${nestedPaths.pop()}.md`
const fullPath = path.join(postsDirectory, ...nestedPaths, fileName)

Resources