url
stringlengths
24
106
html
stringlengths
41
53k
title
stringlengths
0
63
https://javascript.info/intro
Let’s see what’s so special about JavaScript, what we can achieve with it, and what other technologies play well with it. What is JavaScript? JavaScript was initially created to “make web pages alive”. The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads. Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run. In this aspect, JavaScript is very different from another language called Java. Why is it called JavaScript? When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that time, so it was decided that positioning a new language as a “younger brother” of Java would help. But as it evolved, JavaScript became a fully independent language with its own specification called ECMAScript, and now it has no relation to Java at all. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. The browser has an embedded engine sometimes called a “JavaScript virtual machine”. Different engines have different “codenames”. For example: V8 – in Chrome, Opera and Edge. SpiderMonkey – in Firefox. …There are other codenames like “Chakra” for IE, “JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc. The terms above are good to remember because they are used in developer articles on the internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably works in Chrome, Opera and Edge. How do engines work? Engines are complicated. But the basics are easy. The engine (embedded if it’s a browser) reads (“parses”) the script. Then it converts (“compiles”) the script to machine code. And then the machine code runs, pretty fast. The engine applies optimizations at each step of the process. It even watches the compiled script as it runs, analyzes the data that flows through it, and further optimizes the machine code based on that knowledge. What can in-browser JavaScript do? Modern JavaScript is a “safe” programming language. It does not provide low-level access to memory or the CPU, because it was initially created for browsers which do not require it. JavaScript’s capabilities greatly depend on the environment it’s running in. For instance, Node.js supports functions that allow JavaScript to read/write arbitrary files, perform network requests, etc. In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver. For instance, in-browser JavaScript is able to: Add new HTML to the page, change the existing content, modify styles. React to user actions, run on mouse clicks, pointer movements, key presses. Send requests over the network to remote servers, download and upload files (so-called AJAX and COMET technologies). Get and set cookies, ask questions to the visitor, show messages. Remember the data on the client-side (“local storage”). What CAN’T in-browser JavaScript do? JavaScript’s abilities in the browser are limited to protect the user’s safety. The aim is to prevent an evil webpage from accessing private information or harming the user’s data. Examples of such restrictions include: JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS functions. Modern browsers allow it to work with files, but the access is limited and only provided if the user does certain actions, like “dropping” a file into a browser window or selecting it via an <input> tag. There are ways to interact with the camera/microphone and other devices, but they require a user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the NSA. Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other page if they come from different sites (from a different domain, protocol or port). This is called the “Same Origin Policy”. To work around that, both pages must agree for data exchange and must contain special JavaScript code that handles it. We’ll cover that in the tutorial. This limitation is, again, for the user’s safety. A page from http://anysite.com which a user has opened must not be able to access another browser tab with the URL http://gmail.com, for example, and steal information from there. JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that’s a safety limitation. Such limitations do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugins/extensions which may ask for extended permissions. What makes JavaScript unique? There are at least three great things about JavaScript: Full integration with HTML/CSS. Simple things are done simply. Supported by all major browsers and enabled by default. JavaScript is the only browser technology that combines these three things. That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating browser interfaces. That said, JavaScript can be used to create servers, mobile applications, etc. Languages “over” JavaScript The syntax of JavaScript does not suit everyone’s needs. Different people want different features. That’s to be expected, because projects and requirements are different for everyone. So, recently a plethora of new languages appeared, which are transpiled (converted) to JavaScript before they run in the browser. Modern tools make the transpilation very fast and transparent, actually allowing developers to code in another language and auto-converting it “under the hood”. Examples of such languages: CoffeeScript is “syntactic sugar” for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it. TypeScript is concentrated on adding “strict data typing” to simplify the development and support of complex systems. It is developed by Microsoft. Flow also adds data typing, but in a different way. Developed by Facebook. Dart is a standalone language that has its own engine that runs in non-browser environments (like mobile apps), but also can be transpiled to JavaScript. Developed by Google. Brython is a Python transpiler to JavaScript that enables the writing of applications in pure Python without JavaScript. Kotlin is a modern, concise and safe programming language that can target the browser or Node. There are more. Of course, even if we use one of these transpiled languages, we should also know JavaScript to really understand what we’re doing. Summary JavaScript was initially created as a browser-only language, but it is now used in many other environments as well. Today, JavaScript has a unique position as the most widely-adopted browser language, fully integrated with HTML/CSS. There are many languages that get “transpiled” to JavaScript and provide certain features. It is recommended to take a look at them, at least briefly, after mastering JavaScript.
An Introduction to JavaScript
https://javascript.info/manuals-specifications
This book is a tutorial. It aims to help you gradually learn the language. But once you’re familiar with the basics, you’ll need other resources. Specification The ECMA-262 specification contains the most in-depth, detailed and formalized information about JavaScript. It defines the language. But being that formalized, it’s difficult to understand at first. So if you need the most trustworthy source of information about the language details, the specification is the right place. But it’s not for everyday use. A new specification version is released every year. Between these releases, the latest specification draft is at https://tc39.es/ecma262/. To read about new bleeding-edge features, including those that are “almost standard” (so-called “stage 3”), see proposals at https://github.com/tc39/proposals. Also, if you’re developing for the browser, then there are other specifications covered in the second part of the tutorial. Manuals MDN (Mozilla) JavaScript Reference is the main manual with examples and other information. It’s great to get in-depth information about individual language functions, methods etc. You can find it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference. Although, it’s often best to use an internet search instead. Just use “MDN [term]” in the query, e.g. https://google.com/search?q=MDN+parseInt to search for the parseInt function. Compatibility tables JavaScript is a developing language, new features get added regularly. To see their support among browser-based and other engines, see: https://caniuse.com – per-feature tables of support, e.g. to see which engines support modern cryptography functions: https://caniuse.com/#feat=cryptography. https://kangax.github.io/compat-table – a table with language features and engines that support those or don’t support. All these resources are useful in real-life development, as they contain valuable information about language details, their support, etc. Please remember them (or this page) for the cases when you need in-depth information about a particular feature.
Manuals and specifications
https://javascript.info/getting-started
About the JavaScript language and the environment to develop with it. An Introduction to JavaScript Manuals and specifications Code editors Developer console
An introduction
https://javascript.info/privacy
We value your privacy. We never sell your data to third party. We only use it for intended purposes. And we only send you newsletters if you willingly subscribe. This Privacy Policy (the “Policy”) discloses the privacy practices of Techlead LLC, the legal entity behind the site, and other people of the team (referred to collectively as “we”, “us”, “our”). The Policy governs how we use and protect personal information that we collect when you visit our website, use our services, or otherwise engage with us. INFORMATION WE COLLECT We collect personal information in the following ways: INFORMATION THAT YOU PROVIDE TO US DIRECTLY We gather information that you provide to us when you: purchase products or services from us subscribe to our newsletters and mailing lists fill in forms, conduct searches, post content on the website, respond to surveys, or use any other features of our websites make an inquiry, provide feedback, submit correspondence, or make a complaint over the phone, by email, on our websites or by post register for, and update an online account with us (including if you access through Facebook, LinkedIn, Twitter, Google, or another provider) enter into a contract with us sign up for alerts or notifications on our websites, submit a job application, a CV, cover letter, or social media profile to a job vacancy, attend an interview, assessment, or meeting ‘follow’, ‘like’, post to, or interact with, our social media accounts, including Facebook, LinkedIn, Twitter, Pinterest, Instagram, Google+, SnapChat and Slack. The information you provide to us may include (depending on the circumstances): Identity and contact data: title, names, addresses, email addresses, phone numbers or your signature. Account profile data: a username/display name, password, user preferences, picture if you upload it, additional details that you enter and, if you sign up through a social media account, certain information about that account. Limited payment details if you make a payment at our website. We use a secure third-party service, e.g. Stripe or Paypal for payments, so we do not get your credit card number, but we may have information like the last four digits, your name or the country of issue. If you apply for employment: Employment and background data, your academic and work history, qualifications, skills, projects and research that you are involved in, references, proof of your entitlement to work in the relevant country, your national security number, your passport or other identity document details, your current level of remuneration (including benefits), and any other such similar information that you may provide to us. Visual and audio information about yourself: e.g. a photo or video footage, or sound recording. Any other information that you choose to share with us: for example, any information that you provide via correspondence, when you fill out our survey(s), that you share via our website or social media accounts linked to our website, or any information that you choose to provide in person at events, meetings, or over the phone. INFORMATION WE COLLECT THROUGH SERVER TECHNOLOGY We may store IP addresses in our server logs to ensure network security, the ability of our system to resist unlawful or malicious actions, such as ‘denial of service’ attacks. We can also store additional technical details about your visits for diagnostic purposes, to fix errors in our service if they occur. INFORMATION WE COLLECT THROUGH ONLINE TECHNOLOGY Technologies such as cookies, beacons, tags, local storage, and scripts are used by us and our affiliates, and other companies, such as third party technology service providers and web analytics providers. These technologies make it easier for you to navigate our website and to help us manage the content on our website and are used to analyze trends, administer the sites, track users’ movements around the site (including which site you clicked from to arrive at our site), and gather demographic information about our user base. Cookies are small files that a site or its service provider transfers to your computer’s hard drive through your Web browser (if you don’t disable it) that enables the site’s or service provider’s systems to recognize your browser and capture and remember certain information. They are used to help us understand your preferences based on previous or current site activity, which enables us to provide you with improved services. Cookies also help us compile aggregate data about site traffic and site interaction so that we can offer better site experiences and tools in the future. For instance, we use Google Analytics and Yandex Metrika to collect statistics about our site. SPECIAL CATEGORIES OF DATA Special categories of particularly sensitive personal information require higher levels of protection. We do not collect such information when you visit our website or purchase or subscribe for a newsletter or ask for services, as we need further justification for that. These so-called “special categories of data” include details about your race or ethnicity, religious or philosophical beliefs, sex life, sexual orientation, political opinions, trade union membership, information about your health and genetic and biometric data,criminal convictions and offenses. The reasons for collecting, storing and using this type of personal information: you apply to work for us, where it is necessary to carry out our legal obligations or exercise rights in connection with employment where it is necessary for reasons of substantial public interest where it is necessary in relation to legal claims where it is necessary to protect your interests (or someone else’s interests) and you are not capable of giving your consent where you have already made the information public In limited circumstances, we may request your written consent to allow us to use certain particularly sensitive data. If we do so, we will provide you with full details of the information that we would like and the reason we need it, so that you can carefully consider whether you wish to consent. USING PERSONAL INFORMATION HOW WE USE INFORMATION WE COLLECT We use your information for the following purposes: To provide access to our website in a manner convenient and optimal and with personalized content relevant to you (on the basis of our legitimate interest to ensure our website is presented in an effective and optimal manner). To register and maintain your website account (on the basis of our terms of service). To store your personal settings. To process and fulfill your orders for products and services (on the basis of performing our contract with you). To process and facilitate transactions and payments, and recover money owed to us (on the basis of performing our contract with you, and on the basis of our legitimate interest to recover debts due). To monitor your account and use of services to ensure compliance with our end-user agreements and prevent and identify unlawful content use and violations (on the basis of our legitimate interests to operate a safe and lawful business, or where we have a legal obligation to do so). To enable you to communicate with other website users and clients (on the basis of your consent where we have requested it, or on the basis of performing our contract with you). To manage our relationship with you, which will include notifying you about changes to our terms of service or privacy policy, and asking you to leave a review or take a survey (on the basis of performing our contract with you, to comply with our legal obligations, and our legitimate interest in keeping our records updated and study how our website and services are used). To conduct business with you or your employer, including to contact you and manage and facilitate our business relationship with you and your employer (on the basis of performing our contract with you, and our legitimate interest in running our business). To provide customer service and support, like dealing with inquiries or complaints about the website, which may include sharing your information with our website developer, IT support provider, and payment services provider as necessary (on the basis of performing our contract with you, our legitimate interest in providing the correct products and services to our website users, and to comply with our legal obligations). To enable you to take part in prize drawings, competitions, and surveys (on the basis of performing our contract with you, and our legitimate interest in studying how our website and services are used, to develop them, and to grow our business). To work with you and undertake projects with you, including to process any proposals that you submit to us (on the basis of our contract with you, and our legitimate interest in running our business). For recruitment, including to process any job applications you submit to us, whether directly or via an agent or recruiter including sharing your information with our third party recruitment agencies (on the basis of our legitimate interest to recruit new employees or contractors). To carry out marketing and let you know about our news, events, new website features products or services that we believe may interest you, including sharing your information with our marketing services providers (either on the basis of your consent where we have requested it, or our legitimate interests to provide you with marketing communications where we may lawfully do so). To deliver relevant website content and advertisements to you and measure or understand the effectiveness of the advertising we serve to you (on the basis of our legitimate interests in studying how our website/services are used, to develop them, to grow our business and to inform our marketing strategy). To interact with users on social media platforms (on the basis of our legitimate interest in promoting our brand and communicating with interested individuals). To conduct data analytics to improve our website, products/services, marketing, customer relationships and experiences (on the basis of our legitimate interests in defining types of customers for our website and services, to keep our website updated and relevant, to develop our business, to provide the right kinds of products and services to our customers, and to inform our business and marketing strategy). To make suggestions and recommendations by sharing your information with selected third parties such as sponsors and partners, so they can contact you about things that may interest you (either on the basis of your consent where we have requested it, or on the basis of our legitimate interest to share details of conference attendees with our co-presenters and sponsors). To carry out marketing research and user testing to assess the levels of satisfaction of existing and proposed products and services (on the basis of our legitimate interest in carrying out research, providing the right kinds of products and services to our customers). To protect, investigate, and deter against fraudulent, unauthorized, or illegal activity (on the basis of our legitimate interests to operate a safe and lawful business, or where we have a legal obligation to do so). To enable us to comply with our policies and procedures and enforce our legal rights, and to protect the rights, property or safety of our employees and share your information with our technical and legal advisors (on the basis of our legitimate interests to operate a safe and lawful business, or where we have a legal obligation to do so). We will use your information for the purposes listed above either on the basis of: your consent (where we request it) performance of your contract with us and the provision of our services to you where we need to comply with a legal or regulatory obligation our legitimate interests or those of a third party (see section below for more information). LEGITIMATE INTERESTS As outlined above, in certain circumstances we may use your personal information to pursue legitimate interests of our own or those of third parties. Where we refer to our “legitimate interests”, we mean our legitimate business interests in conducting and managing our business and our relationship with you, including the legitimate interests we have specified in section above. Where we use your information for our legitimate interests, we make sure that we take into account any potential impact that such use may have on you. Our legitimate interests don’t automatically override yours and we won’t use your information if we believe your interests should override ours unless we have other grounds to do so (such as your consent or a legal obligation). If you have any concerns about our processing please refer to details of “Your Rights” section below. HOW WE SHARE AND DISCLOSE PERSONAL INFORMATION We consider your personal information to be a vital part of our relationship with you and do not sell your personal information to third parties. There are, however, certain circumstances in which we may share your personal information with certain third parties, as follows: Our service providers who are acting as processors and who assist us with our administrative or business functions, or in the provision of any of our products/services to you, for instance Paymentwall that accepts credit card payments, or Amazon services that processes email sending. These providers’ privacy policy is described in respective agreements. Other website users and clients who use our websites and/or applications to communicate or otherwise interact with you. Our partners who are involved in providing services to you. Regulators and governmental bodies, authorities and regulators acting as processors or joint controllers who require reporting of processing activities in certain circumstances. Marketing parties which are any selected third party that you consent to our sharing your information with for marketing purposes. Any prospective buyer of our business or assets, only in the event that we wish to sell any part of our business or assets. Other third parties including legal, professional or other advisors, regulatory authorities, courts, law enforcement agencies and government agencies) where necessary to enable us to enforce our legal rights, or to protect the rights, property or safety of our employees or where such disclosure may be permitted or required by law. HOW WE LOOK AFTER YOUR PERSONAL INFORMATION AND HOW LONG WE KEEP IT SECURITY We use administrative, technical, and physical safeguards to protect the security, confidentiality, and integrity of personal data against loss, misuse and unauthorized access, disclosure, alteration, and destruction. We also operate a policy of “privacy by design” by looking for opportunities to minimize the amount of personal information we hold about you. The safeguards we use include: ensuring the physical security of our offices, warehouses, or other sites ensuring the physical and digital security of our equipment and devices by using appropriate password protection and encryption using standard security protocols and mechanisms (such as secure socket layer (SSL) encryption) to transmit sensitive data such as credit card details limiting access to your personal information to those who need to use it in the course of their work If you have any questions about the security of your personal information, please contact us using the methods outlined in the “Contact Us” section below. RETENTION We will keep your information for as long as is necessary to provide you with the services that you have requested from us or for as long as we reasonably require to retain the information for our lawful business purposes, such as for the purposes of exercising our legal rights or where we are permitted to do. HELP KEEP YOUR INFORMATION SAFE You can also play a part in keeping your information safe by: choosing a strong account password, changing it regularly, and using different passwords for different online accounts keeping your login and password details confidential logging out of the website and closing the browser each time you have finished using it, especially when using a shared computer informing us if know or suspect that your account has been compromised, or if someone has accessed your account without your permission keeping your devices protected by using the latest version of your operating system and maintaining any necessary anti-virus software being vigilant to any fraudulent emails that may appear to be from us INTERNATIONAL TRANSFERS OF YOUR INFORMATION Our servers are located in Germany, also we use Amazon services located in the United States of America. Our partners and contractors involved in servicing you (e.g. support agents, course teachers) may be located in other European and Asian countries. If you reside in the European Union, please be advised that your personal data will be processed outside of the European Economic Area (EEA). We will take all steps necessary to ensure that your information is adequately protected and processed in accordance with this Privacy Policy. YOUR RIGHTS: ACCESS AND ACCURACY, UPDATING, CORRECTING, OR DELETING INFORMATION You have certain rights in respect of the information that we hold about you, including: the right to be informed of the ways in which we use your information, as we seek to do in this Privacy Policy the right to ask us not to process your personal data for marketing purposes the right to request access to the information that we hold about you the right to request that we correct or rectify any information that we hold about you which is out of date or incorrect the right to withdraw your consent for our use of your information in reliance of your consent (refer to sections above to see when we are relying on your consent), which you can do by contacting us using any of the details at the top of this Privacy Policy the right to object to our using your information on the basis of our legitimate interests (refer to sections above to see when we are relying on our legitimate interests) (or those of a third party)) and there is something about your particular situation which makes you want to object to processing on this ground the right to receive a copy of any information we hold about you (or request that we transfer this to another service provider) in a structured, commonly-used, machine readable format, in certain circumstances in certain circumstances, the right to ask us to limit or cease processing or erase information we hold about you HOW TO EXERCISE YOUR RIGHTS You may exercise your rights above by contacting us using the methods outlined in the “Contact Us” section below and we will comply with your requests unless we have a lawful reason not to do so. You can opt-out of receiving newsletters or other communications that you previously subscribed by following the opt-out instructions included in each newsletter or communication or by contacting us using the methods outlined in the “Contact Us” section below. Please note that your objection to processing (or withdrawal of any previously given consent) could mean that we are unable to provide you with our services. Even after you have chosen to withdraw your consent we may continue to process your personal information when required or permitted by law, in particular in connection with exercising and defending our legal rights, or meeting our legal and regulatory obligations. WHAT WE NEED FROM YOU TO PROCESS YOUR REQUESTS We may need to request specific information from you to help us confirm your identity and to enable you to exercise the rights set out above. This is a security measure to ensure that personal data is not disclosed to any person who has no right to receive it. We may also contact you to ask you for further information in relation to your request to speed up our response. You will not have to pay a fee to exercise the rights set out above. However, we may charge a reasonable fee if your request is clearly unfounded, repetitive or excessive. Alternatively, we may refuse to comply with your request in these circumstances. We will try to respond to all legitimate requests within one month. Occasionally it may take us longer than a month if your request is particularly complex or you have made a number of requests. In this case, we will notify you and keep you updated. CHILDREN’S PRIVACY Our website is not intended for children. We do not knowingly collect or maintain the personal information of children under the age of 13, and in some jurisdictions under the age of 16. If you are under the age of 13, please do not access our website at any time or in any manner. If we learn that we have collected personal information of children under the age of 13 or 16 (as applicable), we will take appropriate steps to delete that data. SHARING DATA WITH THIRD PARTIES You might provide personal information directly to third parties as a consequence of your interactions with our website and other services offered by us. For example, our website may contain content and links to other third-party websites, plug-ins, and applications that are operated by third parties that may also operate cookies. Clicking on those links or enabling those connections may allow third parties to collect or share data about you. We don’t control these third party websites or cookies, we are not responsible for their privacy statements, and this Privacy Policy does not apply to them. Please check the terms and conditions and privacy policy of the relevant third party website to find out how they collect and use your information. Please be responsible with personal information of others when using our website and the services available on it. We are not responsible for your misuse of personal information, or for the direct relationship between you and others that takes place outside of the website or our services. FOR CALIFORNIA RESIDENTS: YOUR PRIVACY RIGHTS AND DO NOT TRACK DISCLOSURE The Policy is to share your personal information only if you have given us your consent, for instance, by your agreeing to this Privacy Policy through your use of our sites. After obtaining such consent, Safari may in accordance with this Privacy Policy from time to time provide its business partners with contact details for direct marketing purposes of relevant services, products, and programs. If you no longer wish your information to be shared, please let us know, and we will prevent disclosure of your information to such business partners free of charge, or if you have further inquiries regarding our information sharing practices, please let us know using the methods outlined in the “Contact Us” section below. California law requires us to let you know how we respond to web browser Do Not Track (DNT) signals. DNT is a way for users to inform websites and services that they do not want certain information about their webpage visits collected over time and across websites or online services. We do not respond to or honor DNT signals or similar mechanisms transmitted by web browsers at this time. CHANGES TO THIS PRIVACY POLICY Please note that this Policy may change from time to time. We will not reduce your rights under this Policy without your consent. If we make any material changes we will notify you by email or by means of a notice on this website prior to the change becoming effective. CONTACT US The legal entity behind the site is Techlead LLC. Address: Armenia, Yerevan, 0051 Nairi Zaryan 22a. Reg. number: 264.110.1232255. Tax id: 08220384. Email: help@javascript.info.
Privacy Policy
https://javascript.info/terms
Welcome to JavaScript.info! By accessing this website we assume you accept these terms and conditions in full. Do not continue to use javascript.info if you do not accept all of the terms and conditions stated on this page. In short, we do not require anything unusual. Respect yourself and others, respect the license when you republish something. That’s what we do as well. The following terminology applies to these Terms and Conditions, Privacy Statement and Disclaimer Notice and any or all Agreements: “Client”, “You” and “Your” refers to you, the person accessing this website and accepting the Company’s terms and conditions. “The Company”, “Ourselves”, “We”, “Our” and “Us”, refers to Techlead LLC, the legal entity behind the site. “Party”, “Parties”, or “Us”, refers to both the Client and ourselves, or either the Client or ourselves. Any use of the above terminology or other words in the singular, plural, capitalisation and/or he/she or they, are taken as interchangeable and therefore as referring to same. Unless otherwise stated, we and/or and/or our licensors own the intellectual property rights for all material on javascript.info. All intellectual property rights are reserved. You may view and/or print pages from https://javascript.info for your own personal use subject to restrictions set in these terms and conditions. Unless otherwise stated, you must not: Republish material from https://javascript.info, Sell, rent or sub-license material from https://javascript.info, Reproduce, duplicate or copy material from https://javascript.info, Redistribute content from javascript.info (unless content is specifically made for redistribution). The Modern JavaScript Tutorial text is a notable exception. It is licensed as CC-BY-NC-SA (see https://github.com/javascript-tutorial/en. javascript.info/blob/master/LICENSE.md) for details, So it is possible to republish it while obeying the terms of the license. Note that if you republish it on your site, you need to put a link to the original version and don’t put ads (non-commercially). Certain parts of this website offer the opportunity for users to post and exchange opinions, information, material and data (‘Comments’) in areas of the website, and also publish the information about themselves (‘Profile’). Together we refer to them as User Content. We do not screen, edit, publish or review User Content prior to their appearance on the website and User Content do not reflect Our views or opinions. User Content reflect the view and opinion of the person who posts such view or opinion. To the extent permitted by applicable laws We shall not be responsible or liable for the User Content or for any loss cost, liability, damages or expenses caused and or suffered as a result of any use of and/or posting of and/or appearance of the User Content on this website. We reserve the right to monitor all User Content and to remove any User Content which it considers in its absolute discretion to be inappropriate, offensive or otherwise in breach of these Terms and Conditions. You warrant and represent that: You are entitled to post User Content on our website and have all necessary licenses and consents to do so; The User Content do not infringe any intellectual property right, including without limitation copyright, patent or trademark, or other proprietary right of any third party; The User Content do not contain any defamatory, libelous, offensive, indecent or otherwise unlawful material or material which is an invasion of privacy The User Content will not be used to solicit or promote business or custom or present commercial activities or unlawful activity. You hereby grant Us a non-exclusive royalty-free license to use, reproduce, edit and authorize others to use, reproduce and edit any of your Comments in any and all forms, formats or media. To the maximum extent permitted by applicable law, we exclude all representations, warranties and conditions relating to our website and the use of this website (including, without limitation, any warranties implied by law in respect of satisfactory quality, fitness for purpose and/or the use of reasonable care and skill). Nothing in this disclaimer will: limit or exclude our or your liability for death or personal injury resulting from negligence; limit or exclude our or your liability for fraud or fraudulent misrepresentation; limit any of our or your liabilities in any way that is not permitted under applicable law; or exclude any of our or your liabilities that may not be excluded under applicable law. The limitations and exclusions of liability set out in this Section and elsewhere in this disclaimer: (a) are subject to the preceding paragraph; and (b) govern all liabilities arising under the disclaimer or in relation to the subject matter of this disclaimer, including liabilities arising in contract, in tort (including negligence) and for breach of statutory duty. To the extent that the website and the information and services on the website are provided free of charge, we will not be liable for any loss or damage of any nature. This sites makes use of Disqus for comments. It has a separate user authentication system, independent from ours. Occasionally we may include or offer other third-party products or services with clear indication that they belong to a third-party. Third-party sites have separate and independent privacy policies, therefore we have no responsibility or liability for the content and activities of these linked sites. Nonetheless, we seek to protect the integrity of our site and welcome any feedback about these sites. Ebook Terms and Conditions eBook titles purchased cannot be returned, printed, refunded, or exchanged. If you experience technical difficulty in downloading or accessing a title, please contact us at help@javascript.info for assistance. You are permitted to download the eBook but this licence is personal to you, non-exclusive and non-transferrable. You may reproduce and store portions of the eBook content for your personal use. Full-scale reproduction of the contents of the eBook is expressly prohibited. You may not use the eBook on more than one computer system concurrently, make or distribute unauthorised copies of the eBook, or use, copy, modify, or transfer the eBook, in whole or in part, unless you receive our express permission. If you transfer possession of the eBook to a third party, the licence is automatically terminated. You are granted the right to download the eBook you may print pages of the eBook for your personal use and reference in connection with your work. You may create and save bookmarks, highlights and notes as provided by the functionality of the program. You agree to protect the eBook from unauthorised use, reproduction, or distribution. You further agree not to translate, decompile, or disassemble the eBook except to the extent permitted under applicable law. Multi-use configurations or network distribution of the eBook is expressly prohibited. Additionally, the contents of the eBook is published under CC-BY-NC-SA license, see https://creativecommons.org/licenses/by-nc-sa/3.0/legalcode. In short, you may distribute, adapt and reuse it under following conditions: Attribution: write about the source (this site), add a link to our website. Noncommercial use only. Your works based on this code must use the same license. Disclaimer The ebook is provided “as is”, without warranty of any kind, expressed or implied including without limitations, accuracy, omissions, completeness or implied warranties or suitability or fitness for a particular purpose or other incidental damages arising out of the use or the inability to use the ebook. You acknowledge that the use of this service is entirely at your own risk. You acknowledge that you have read these Terms of Usage, and agree to be bound by these terms and conditions. The legal entity behind the site is Techlead LLC. Address: Armenia, Yerevan, 0051 Nairi Zaryan 22a. Reg. number: 264.110.1232255. Tax id: 08220384. To contact, please mail to help@javascript.info.
Terms of Usage
https://javascript.info/fetch-crossorigin
If we send a fetch request to another web-site, it will probably fail. For instance, let’s try fetching http://example.com: try { await fetch('http://example.com'); } catch(err) { alert(err); // Failed to fetch } Fetch fails, as expected. The core concept here is origin – a domain/port/protocol triplet. Cross-origin requests – those sent to another domain (even a subdomain) or protocol or port – require special headers from the remote side. That policy is called “CORS”: Cross-Origin Resource Sharing. Why is CORS needed? A brief history CORS exists to protect the internet from evil hackers. Seriously. Let’s make a very brief historical digression. For many years a script from one site could not access the content of another site. That simple, yet powerful rule was a foundation of the internet security. E.g. an evil script from website hacker.com could not access the user’s mailbox at website gmail.com. People felt safe. JavaScript also did not have any special methods to perform network requests at that time. It was a toy language to decorate a web page. But web developers demanded more power. A variety of tricks were invented to work around the limitation and make requests to other websites. Using forms One way to communicate with another server was to submit a <form> there. People submitted it into <iframe>, just to stay on the current page, like this: <!-- form target --> <iframe name="iframe"></iframe> <!-- a form could be dynamically generated and submitted by JavaScript --> <form target="iframe" method="POST" action="http://another.com/…"> ... </form> So, it was possible to make a GET/POST request to another site, even without networking methods, as forms can send data anywhere. But as it’s forbidden to access the content of an <iframe> from another site, it wasn’t possible to read the response. To be precise, there were actually tricks for that, they required special scripts at both the iframe and the page. So the communication with the iframe was technically possible. Right now there’s no point to go into details, let these dinosaurs rest in peace. Using scripts Another trick was to use a script tag. A script could have any src, with any domain, like <script src="http://another.com/…">. It’s possible to execute a script from any website. If a website, e.g. another.com intended to expose data for this kind of access, then a so-called “JSONP (JSON with padding)” protocol was used. Here’s how it worked. Let’s say we, at our site, need to get the data from http://another.com, such as the weather: First, in advance, we declare a global function to accept the data, e.g. gotWeather. // 1. Declare the function to process the weather data function gotWeather({ temperature, humidity }) { alert(`temperature: ${temperature}, humidity: ${humidity}`); } Then we make a <script> tag with src="http://another.com/weather.json?callback=gotWeather", using the name of our function as the callback URL-parameter. let script = document.createElement('script'); script.src = `http://another.com/weather.json?callback=gotWeather`; document.body.append(script); The remote server another.com dynamically generates a script that calls gotWeather(...) with the data it wants us to receive. // The expected answer from the server looks like this: gotWeather({ temperature: 25, humidity: 78 }); When the remote script loads and executes, gotWeather runs, and, as it’s our function, we have the data. That works, and doesn’t violate security, because both sides agreed to pass the data this way. And, when both sides agree, it’s definitely not a hack. There are still services that provide such access, as it works even for very old browsers. After a while, networking methods appeared in browser JavaScript. At first, cross-origin requests were forbidden. But as a result of long discussions, cross-origin requests were allowed, but with any new capabilities requiring an explicit allowance by the server, expressed in special headers. Safe requests There are two types of cross-origin requests: Safe requests. All the others. Safe Requests are simpler to make, so let’s start with them. A request is safe if it satisfies two conditions: Safe method: GET, POST or HEAD Safe headers – the only allowed custom headers are: Accept, Accept-Language, Content-Language, Content-Type with the value application/x-www-form-urlencoded, multipart/form-data or text/plain. Any other request is considered “unsafe”. For instance, a request with PUT method or with an API-Key HTTP-header does not fit the limitations. The essential difference is that a safe request can be made with a <form> or a <script>, without any special methods. So, even a very old server should be ready to accept a safe request. Contrary to that, requests with non-standard headers or e.g. method DELETE can’t be created this way. For a long time JavaScript was unable to do such requests. So an old server may assume that such requests come from a privileged source, “because a webpage is unable to send them”. When we try to make a unsafe request, the browser sends a special “preflight” request that asks the server – does it agree to accept such cross-origin requests, or not? And, unless the server explicitly confirms that with headers, an unsafe request is not sent. Now we’ll go into details. CORS for safe requests If a request is cross-origin, the browser always adds the Origin header to it. For instance, if we request https://anywhere.com/request from https://javascript.info/page, the headers will look like: GET /request Host: anywhere.com Origin: https://javascript.info ... As you can see, the Origin header contains exactly the origin (domain/protocol/port), without a path. The server can inspect the Origin and, if it agrees to accept such a request, add a special header Access-Control-Allow-Origin to the response. That header should contain the allowed origin (in our case https://javascript.info), or a star *. Then the response is successful, otherwise it’s an error. The browser plays the role of a trusted mediator here: It ensures that the correct Origin is sent with a cross-origin request. It checks for permitting Access-Control-Allow-Origin in the response, if it exists, then JavaScript is allowed to access the response, otherwise it fails with an error. Here’s an example of a permissive server response: 200 OK Content-Type:text/html; charset=UTF-8 Access-Control-Allow-Origin: https://javascript.info Response headers For cross-origin request, by default JavaScript may only access so-called “safe” response headers: Cache-Control Content-Language Content-Length Content-Type Expires Last-Modified Pragma Accessing any other response header causes an error. To grant JavaScript access to any other response header, the server must send the Access-Control-Expose-Headers header. It contains a comma-separated list of unsafe header names that should be made accessible. For example: 200 OK Content-Type:text/html; charset=UTF-8 Content-Length: 12345 Content-Encoding: gzip API-Key: 2c9de507f2c54aa1 Access-Control-Allow-Origin: https://javascript.info Access-Control-Expose-Headers: Content-Encoding,API-Key With such an Access-Control-Expose-Headers header, the script is allowed to read the Content-Encoding and API-Key headers of the response. “Unsafe” requests We can use any HTTP-method: not just GET/POST, but also PATCH, DELETE and others. Some time ago no one could even imagine that a webpage could make such requests. So there may still exist webservices that treat a non-standard method as a signal: “That’s not a browser”. They can take it into account when checking access rights. So, to avoid misunderstandings, any “unsafe” request – that couldn’t be done in the old times, the browser does not make such requests right away. First, it sends a preliminary, so-called “preflight” request, to ask for permission. A preflight request uses the method OPTIONS, no body and three headers: Access-Control-Request-Method header has the method of the unsafe request. Access-Control-Request-Headers header provides a comma-separated list of its unsafe HTTP-headers. Origin header tells from where the request came. (such as https://javascript.info) If the server agrees to serve the requests, then it should respond with empty body, status 200 and headers: Access-Control-Allow-Origin must be either * or the requesting origin, such as https://javascript.info, to allow it. Access-Control-Allow-Methods must have the allowed method. Access-Control-Allow-Headers must have a list of allowed headers. Additionally, the header Access-Control-Max-Age may specify a number of seconds to cache the permissions. So the browser won’t have to send a preflight for subsequent requests that satisfy given permissions. Let’s see how it works step-by-step on the example of a cross-origin PATCH request (this method is often used to update data): let response = await fetch('https://site.com/service.json', { method: 'PATCH', headers: { 'Content-Type': 'application/json', 'API-Key': 'secret' } }); There are three reasons why the request is unsafe (one is enough): Method PATCH Content-Type is not one of: application/x-www-form-urlencoded, multipart/form-data, text/plain. “Unsafe” API-Key header. Step 1 (preflight request) Prior to sending such a request, the browser, on its own, sends a preflight request that looks like this: OPTIONS /service.json Host: site.com Origin: https://javascript.info Access-Control-Request-Method: PATCH Access-Control-Request-Headers: Content-Type,API-Key Method: OPTIONS. The path – exactly the same as the main request: /service.json. Cross-origin special headers: Origin – the source origin. Access-Control-Request-Method – requested method. Access-Control-Request-Headers – a comma-separated list of “unsafe” headers. Step 2 (preflight response) The server should respond with status 200 and the headers: Access-Control-Allow-Origin: https://javascript.info Access-Control-Allow-Methods: PATCH Access-Control-Allow-Headers: Content-Type,API-Key. That allows future communication, otherwise an error is triggered. If the server expects other methods and headers in the future, it makes sense to allow them in advance by adding them to the list. For example, this response also allows PUT, DELETE and additional headers: 200 OK Access-Control-Allow-Origin: https://javascript.info Access-Control-Allow-Methods: PUT,PATCH,DELETE Access-Control-Allow-Headers: API-Key,Content-Type,If-Modified-Since,Cache-Control Access-Control-Max-Age: 86400 Now the browser can see that PATCH is in Access-Control-Allow-Methods and Content-Type,API-Key are in the list Access-Control-Allow-Headers, so it sends out the main request. If there’s the header Access-Control-Max-Age with a number of seconds, then the preflight permissions are cached for the given time. The response above will be cached for 86400 seconds (one day). Within this timeframe, subsequent requests will not cause a preflight. Assuming that they fit the cached allowances, they will be sent directly. Step 3 (actual request) When the preflight is successful, the browser now makes the main request. The process here is the same as for safe requests. The main request has the Origin header (because it’s cross-origin): PATCH /service.json Host: site.com Content-Type: application/json API-Key: secret Origin: https://javascript.info Step 4 (actual response) The server should not forget to add Access-Control-Allow-Origin to the main response. A successful preflight does not relieve from that: Access-Control-Allow-Origin: https://javascript.info Then JavaScript is able to read the main server response. Please note: Preflight request occurs “behind the scenes”, it’s invisible to JavaScript. JavaScript only gets the response to the main request or an error if there’s no server permission. Credentials A cross-origin request initiated by JavaScript code by default does not bring any credentials (cookies or HTTP authentication). That’s uncommon for HTTP-requests. Usually, a request to http://site.com is accompanied by all cookies from that domain. Cross-origin requests made by JavaScript methods on the other hand are an exception. For example, fetch('http://another.com') does not send any cookies, even those (!) that belong to another.com domain. Why? That’s because a request with credentials is much more powerful than without them. If allowed, it grants JavaScript the full power to act on behalf of the user and access sensitive information using their credentials. Does the server really trust the script that much? Then it must explicitly allow requests with credentials with an additional header. To send credentials in fetch, we need to add the option credentials: "include", like this: fetch('http://another.com', { credentials: "include" }); Now fetch sends cookies originating from another.com with request to that site. If the server agrees to accept the request with credentials, it should add a header Access-Control-Allow-Credentials: true to the response, in addition to Access-Control-Allow-Origin. For example: 200 OK Access-Control-Allow-Origin: https://javascript.info Access-Control-Allow-Credentials: true Please note: Access-Control-Allow-Origin is prohibited from using a star * for requests with credentials. Like shown above, it must provide the exact origin there. That’s an additional safety measure, to ensure that the server really knows who it trusts to make such requests. Summary From the browser point of view, there are two kinds of cross-origin requests: “safe” and all the others. “Safe” requests must satisfy the following conditions: Method: GET, POST or HEAD. Headers – we can set only: Accept Accept-Language Content-Language Content-Type to the value application/x-www-form-urlencoded, multipart/form-data or text/plain. The essential difference is that safe requests were doable since ancient times using <form> or <script> tags, while unsafe were impossible for browsers for a long time. So, the practical difference is that safe requests are sent right away, with the Origin header, while for the other ones the browser makes a preliminary “preflight” request, asking for permission. For safe requests: → The browser sends the Origin header with the origin. ← For requests without credentials (not sent by default), the server should set: Access-Control-Allow-Origin to * or same value as Origin ← For requests with credentials, the server should set: Access-Control-Allow-Origin to same value as Origin Access-Control-Allow-Credentials to true Additionally, to grant JavaScript access to any response headers except Cache-Control, Content-Language, Content-Type, Expires, Last-Modified or Pragma, the server should list the allowed ones in Access-Control-Expose-Headers header. For unsafe requests, a preliminary “preflight” request is issued before the requested one: → The browser sends an OPTIONS request to the same URL, with the headers: Access-Control-Request-Method has requested method. Access-Control-Request-Headers lists unsafe requested headers. ← The server should respond with status 200 and the headers: Access-Control-Allow-Methods with a list of allowed methods, Access-Control-Allow-Headers with a list of allowed headers, Access-Control-Max-Age with a number of seconds to cache the permissions. Then the actual request is sent, and the previous “safe” scheme is applied. Tasks Why do we need Origin? importance: 5 As you probably know, there’s HTTP-header Referer, that usually contains an url of the page which initiated a network request. For instance, when fetching http://google.com from http://javascript.info/some/url, the headers look like this: Accept: */* Accept-Charset: utf-8 Accept-Encoding: gzip,deflate,sdch Connection: keep-alive Host: google.com Origin: http://javascript.info Referer: http://javascript.info/some/url As you can see, both Referer and Origin are present. The questions: Why Origin is needed, if Referer has even more information? Is it possible that there’s no Referer or Origin, or is it incorrect? solution
Fetch: Cross-Origin Requests
https://javascript.info/import-export
Export and import directives have several syntax variants. In the previous article we saw a simple use, now let’s explore more examples. Export before declarations We can label any declaration as exported by placing export before it, be it a variable, function or a class. For instance, here all exports are valid: // export an array export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // export a constant export const MODULES_BECAME_STANDARD_YEAR = 2015; // export a class export class User { constructor(name) { this.name = name; } } No semicolons after export class/function Please note that export before a class or a function does not make it a function expression. It’s still a function declaration, albeit exported. Most JavaScript style guides don’t recommend semicolons after function and class declarations. That’s why there’s no need for a semicolon at the end of export class and export function: export function sayHi(user) { alert(`Hello, ${user}!`); } // no ; at the end Export apart from declarations Also, we can put export separately. Here we first declare, and then export: // 📁 say.js function sayHi(user) { alert(`Hello, ${user}!`); } function sayBye(user) { alert(`Bye, ${user}!`); } export {sayHi, sayBye}; // a list of exported variables …Or, technically we could put export above functions as well. Import * Usually, we put a list of what to import in curly braces import {...}, like this: // 📁 main.js import {sayHi, sayBye} from './say.js'; sayHi('John'); // Hello, John! sayBye('John'); // Bye, John! But if there’s a lot to import, we can import everything as an object using import * as <obj>, for instance: // 📁 main.js import * as say from './say.js'; say.sayHi('John'); say.sayBye('John'); At first sight, “import everything” seems such a cool thing, short to write, why should we ever explicitly list what we need to import? Well, there are few reasons. Explicitly listing what to import gives shorter names: sayHi() instead of say.sayHi(). Explicit list of imports gives better overview of the code structure: what is used and where. It makes code support and refactoring easier. Don’t be afraid to import too much Modern build tools, such as webpack and others, bundle modules together and optimize them to speedup loading. They also removed unused imports. For instance, if you import * as library from a huge code library, and then use only few methods, then unused ones will not be included into the optimzed bundle. Import “as” We can also use as to import under different names. For instance, let’s import sayHi into the local variable hi for brevity, and import sayBye as bye: // 📁 main.js import {sayHi as hi, sayBye as bye} from './say.js'; hi('John'); // Hello, John! bye('John'); // Bye, John! Export “as” The similar syntax exists for export. Let’s export functions as hi and bye: // 📁 say.js ... export {sayHi as hi, sayBye as bye}; Now hi and bye are official names for outsiders, to be used in imports: // 📁 main.js import * as say from './say.js'; say.hi('John'); // Hello, John! say.bye('John'); // Bye, John! Export default In practice, there are mainly two kinds of modules. Modules that contain a library, pack of functions, like say.js above. Modules that declare a single entity, e.g. a module user.js exports only class User. Mostly, the second approach is preferred, so that every “thing” resides in its own module. Naturally, that requires a lot of files, as everything wants its own module, but that’s not a problem at all. Actually, code navigation becomes easier if files are well-named and structured into folders. Modules provide a special export default (“the default export”) syntax to make the “one thing per module” way look better. Put export default before the entity to export: // 📁 user.js export default class User { // just add "default" constructor(name) { this.name = name; } } There may be only one export default per file. …And then import it without curly braces: // 📁 main.js import User from './user.js'; // not {User}, just User new User('John'); Imports without curly braces look nicer. A common mistake when starting to use modules is to forget curly braces at all. So, remember, import needs curly braces for named exports and doesn’t need them for the default one. Named export Default export export class User {...} export default class User {...} import {User} from ... import User from ... Technically, we may have both default and named exports in a single module, but in practice people usually don’t mix them. A module has either named exports or the default one. As there may be at most one default export per file, the exported entity may have no name. For instance, these are all perfectly valid default exports: export default class { // no class name constructor() { ... } } export default function(user) { // no function name alert(`Hello, ${user}!`); } // export a single value, without making a variable export default ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; Not giving a name is fine, because there is only one export default per file, so import without curly braces knows what to import. Without default, such an export would give an error: export class { // Error! (non-default export needs a name) constructor() {} } The “default” name In some situations the default keyword is used to reference the default export. For example, to export a function separately from its definition: function sayHi(user) { alert(`Hello, ${user}!`); } // same as if we added "export default" before the function export {sayHi as default}; Or, another situation, let’s say a module user.js exports one main “default” thing, and a few named ones (rarely the case, but it happens): // 📁 user.js export default class User { constructor(name) { this.name = name; } } export function sayHi(user) { alert(`Hello, ${user}!`); } Here’s how to import the default export along with a named one: // 📁 main.js import {default as User, sayHi} from './user.js'; new User('John'); And, finally, if importing everything * as an object, then the default property is exactly the default export: // 📁 main.js import * as user from './user.js'; let User = user.default; // the default export new User('John'); A word against default exports Named exports are explicit. They exactly name what they import, so we have that information from them; that’s a good thing. Named exports force us to use exactly the right name to import: import {User} from './user.js'; // import {MyUser} won't work, the name must be {User} …While for a default export, we always choose the name when importing: import User from './user.js'; // works import MyUser from './user.js'; // works too // could be import Anything... and it'll still work So team members may use different names to import the same thing, and that’s not good. Usually, to avoid that and keep the code consistent, there’s a rule that imported variables should correspond to file names, e.g: import User from './user.js'; import LoginForm from './loginForm.js'; import func from '/path/to/func.js'; ... Still, some teams consider it a serious drawback of default exports. So they prefer to always use named exports. Even if only a single thing is exported, it’s still exported under a name, without default. That also makes re-export (see below) a little bit easier. Re-export “Re-export” syntax export ... from ... allows to import things and immediately export them (possibly under another name), like this: export {sayHi} from './say.js'; // re-export sayHi export {default as User} from './user.js'; // re-export default Why would that be needed? Let’s see a practical use case. Imagine, we’re writing a “package”: a folder with a lot of modules, with some of the functionality exported outside (tools like NPM allow us to publish and distribute such packages, but we don’t have to use them), and many modules are just “helpers”, for internal use in other package modules. The file structure could be like this: auth/ index.js user.js helpers.js tests/ login.js providers/ github.js facebook.js ... We’d like to expose the package functionality via a single entry point. In other words, a person who would like to use our package, should import only from the “main file” auth/index.js. Like this: import {login, logout} from 'auth/index.js' The “main file”, auth/index.js exports all the functionality that we’d like to provide in our package. The idea is that outsiders, other programmers who use our package, should not meddle with its internal structure, search for files inside our package folder. We export only what’s necessary in auth/index.js and keep the rest hidden from prying eyes. As the actual exported functionality is scattered among the package, we can import it into auth/index.js and export from it: // 📁 auth/index.js // import login/logout and immediately export them import {login, logout} from './helpers.js'; export {login, logout}; // import default as User and export it import User from './user.js'; export {User}; ... Now users of our package can import {login} from "auth/index.js". The syntax export ... from ... is just a shorter notation for such import-export: // 📁 auth/index.js // re-export login/logout export {login, logout} from './helpers.js'; // re-export the default export as User export {default as User} from './user.js'; ... The notable difference of export ... from compared to import/export is that re-exported modules aren’t available in the current file. So inside the above example of auth/index.js we can’t use re-exported login/logout functions. Re-exporting the default export The default export needs separate handling when re-exporting. Let’s say we have user.js with the export default class User and would like to re-export it: // 📁 user.js export default class User { // ... } We can come across two problems with it: export User from './user.js' won’t work. That would lead to a syntax error. To re-export the default export, we have to write export {default as User}, as in the example above. export * from './user.js' re-exports only named exports, but ignores the default one. If we’d like to re-export both named and default exports, then two statements are needed: export * from './user.js'; // to re-export named exports export {default} from './user.js'; // to re-export the default export Such oddities of re-exporting a default export are one of the reasons why some developers don’t like default exports and prefer named ones. Summary Here are all types of export that we covered in this and previous articles. You can check yourself by reading them and recalling what they mean: Before declaration of a class/function/…: export [default] class/function/variable ... Standalone export: export {x [as y], ...}. Re-export: export {x [as y], ...} from "module" export * from "module" (doesn’t re-export default). export {default [as y]} from "module" (re-export default). Import: Importing named exports: import {x [as y], ...} from "module" Importing the default export: import x from "module" import {default as x} from "module" Import all: import * as obj from "module" Import the module (its code runs), but do not assign any of its exports to variables: import "module" We can put import/export statements at the top or at the bottom of a script, that doesn’t matter. So, technically this code is fine: sayHi(); // ... import {sayHi} from './say.js'; // import at the end of the file In practice imports are usually at the start of the file, but that’s only for more convenience. Please note that import/export statements don’t work if inside {...}. A conditional import, like this, won’t work: if (something) { import {sayHi} from "./say.js"; // Error: import must be at top level } …But what if we really need to import something conditionally? Or at the right time? Like, load a module upon request, when it’s really needed? We’ll see dynamic imports in the next article.
Export and Import
https://javascript.info/script-async-defer
In modern websites, scripts are often “heavier” than HTML: their download size is larger, and processing time is also longer. When the browser loads HTML and comes across a <script>...</script> tag, it can’t continue building the DOM. It must execute the script right now. The same happens for external scripts <script src="..."></script>: the browser must wait for the script to download, execute the downloaded script, and only then can it process the rest of the page. That leads to two important issues: Scripts can’t see DOM elements below them, so they can’t add handlers etc. If there’s a bulky script at the top of the page, it “blocks the page”. Users can’t see the page content till it downloads and runs: <p>...content before script...</p> <script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script> <!-- This isn't visible until the script loads --> <p>...content after script...</p> There are some workarounds to that. For instance, we can put a script at the bottom of the page. Then it can see elements above it, and it doesn’t block the page content from showing: <body> ...all content is above the script... <script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script> </body> But this solution is far from perfect. For example, the browser notices the script (and can start downloading it) only after it downloaded the full HTML document. For long HTML documents, that may be a noticeable delay. Such things are invisible for people using very fast connections, but many people in the world still have slow internet speeds and use a far-from-perfect mobile internet connection. Luckily, there are two <script> attributes that solve the problem for us: defer and async. defer The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built. Here’s the same example as above, but with defer: <p>...content before script...</p> <script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script> <!-- visible immediately --> <p>...content after script...</p> In other words: Scripts with defer never block the page. Scripts with defer always execute when the DOM is ready (but before DOMContentLoaded event). The following example demonstrates the second part: <p>...content before scripts...</p> <script> document.addEventListener('DOMContentLoaded', () => alert("DOM ready after defer!")); </script> <script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script> <p>...content after scripts...</p> The page content shows up immediately. DOMContentLoaded event handler waits for the deferred script. It only triggers when the script is downloaded and executed. Deferred scripts keep their relative order, just like regular scripts. Let’s say, we have two deferred scripts: the long.js and then small.js: <script defer src="https://javascript.info/article/script-async-defer/long.js"></script> <script defer src="https://javascript.info/article/script-async-defer/small.js"></script> Browsers scan the page for scripts and download them in parallel, to improve performance. So in the example above both scripts download in parallel. The small.js probably finishes first. …But the defer attribute, besides telling the browser “not to block”, ensures that the relative order is kept. So even though small.js loads first, it still waits and runs after long.js executes. That may be important for cases when we need to load a JavaScript library and then a script that depends on it. The defer attribute is only for external scripts The defer attribute is ignored if the <script> tag has no src. async The async attribute is somewhat like defer. It also makes the script non-blocking. But it has important differences in the behavior. The async attribute means that a script is completely independent: The browser doesn’t block on async scripts (like defer). Other scripts don’t wait for async scripts, and async scripts don’t wait for them. DOMContentLoaded and async scripts don’t wait for each other: DOMContentLoaded may happen both before an async script (if an async script finishes loading after the page is complete) …or after an async script (if an async script is short or was in HTTP-cache) In other words, async scripts load in the background and run when ready. The DOM and other scripts don’t wait for them, and they don’t wait for anything. A fully independent script that runs when loaded. As simple, as it can get, right? Here’s an example similar to what we’ve seen with defer: two scripts long.js and small.js, but now with async instead of defer. They don’t wait for each other. Whatever loads first (probably small.js) – runs first: <p>...content before scripts...</p> <script> document.addEventListener('DOMContentLoaded', () => alert("DOM ready!")); </script> <script async src="https://javascript.info/article/script-async-defer/long.js"></script> <script async src="https://javascript.info/article/script-async-defer/small.js"></script> <p>...content after scripts...</p> The page content shows up immediately: async doesn’t block it. DOMContentLoaded may happen both before and after async, no guarantees here. A smaller script small.js goes second, but probably loads before long.js, so small.js runs first. Although, it might be that long.js loads first, if cached, then it runs first. In other words, async scripts run in the “load-first” order. Async scripts are great when we integrate an independent third-party script into the page: counters, ads and so on, as they don’t depend on our scripts, and our scripts shouldn’t wait for them: <!-- Google Analytics is usually added like this --> <script async src="https://google-analytics.com/analytics.js"></script> The async attribute is only for external scripts Just like defer, the async attribute is ignored if the <script> tag has no src. Dynamic scripts There’s one more important way of adding a script to the page. We can create a script and append it to the document dynamically using JavaScript: let script = document.createElement('script'); script.src = "/article/script-async-defer/long.js"; document.body.append(script); // (*) The script starts loading as soon as it’s appended to the document (*). Dynamic scripts behave as “async” by default. That is: They don’t wait for anything, nothing waits for them. The script that loads first – runs first (“load-first” order). This can be changed if we explicitly set script.async=false. Then scripts will be executed in the document order, just like defer. In this example, loadScript(src) function adds a script and also sets async to false. So long.js always runs first (as it’s added first): function loadScript(src) { let script = document.createElement('script'); script.src = src; script.async = false; document.body.append(script); } // long.js runs first because of async=false loadScript("/article/script-async-defer/long.js"); loadScript("/article/script-async-defer/small.js"); Without script.async=false, scripts would execute in default, load-first order (the small.js probably first). Again, as with the defer, the order matters if we’d like to load a library and then another script that depends on it. Summary Both async and defer have one common thing: downloading of such scripts doesn’t block page rendering. So the user can read page content and get acquainted with the page immediately. But there are also essential differences between them: Order DOMContentLoaded async Load-first order. Their document order doesn’t matter – which loads first runs first Irrelevant. May load and execute while the document has not yet been fully downloaded. That happens if scripts are small or cached, and the document is long enough. defer Document order (as they go in the document). Execute after the document is loaded and parsed (they wait if needed), right before DOMContentLoaded. In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is important. And async is used for independent scripts, like counters or ads. And their relative execution order does not matter. Page without scripts should be usable Please note: if you’re using defer or async, then user will see the page before the script loads. In such case, some graphical components are probably not initialized yet. Don’t forget to put “loading” indication and disable buttons that aren’t functional yet. Let the user clearly see what he can do on the page, and what’s still getting ready.
Scripts: async, defer
https://javascript.info/modules
Modules, introduction Export and Import Dynamic imports
Modules
https://javascript.info/js
Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP. We concentrate on the language itself here, with the minimum of environment-specific notes. An introduction JavaScript Fundamentals Code quality Objects: the basics Data types Advanced working with functions Object properties configuration Prototypes, inheritance Classes Error handling Promises, async/await Generators, advanced iteration Modules Miscellaneous
The JavaScript language
https://javascript.info/ebook
Buy EPUB/PDF for offline reading PDF/EPUB book is an offline version of the tutorial. Buying this book, you support the project and become able to read the tutorial as e-book. You get the whole content as of now, plus 1 year of free updates. download sample Which parts of the tutorial you want? Part I. The JavaScript Language 710+ pages, PDF + EPUB €9 Part II. Browser: Document, Events, Interfaces 300+ pages, PDF + EPUB €9 Part III. Various topics: Network, Regexps, etc. 330+ pages, PDF + EPUB €9 Parts I && II together 2xPDF + 2xEPUB (1000+ pages) €12 Full Tutorial (all 3 parts) 3xEPUB + 3xPDF (1300+ pages) €18 Specify your email The download link will be sent to this address after payment. In case of any difficulty please contact orders@javascript.info. Proceed with payment
https://javascript.info/
PART 1 The JavaScript language PART 2 Browser: Document, Events, Interfaces PART 3 Additional articles The JavaScript language Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP. We concentrate on the language itself here, with the minimum of environment-specific notes. An introduction An Introduction to JavaScript Manuals and specifications Code editors Developer console JavaScript Fundamentals Hello, world! Code structure The modern mode, "use strict" Variables Data types Interaction: alert, prompt, confirm Type Conversions Basic operators, maths Comparisons Conditional branching: if, '?' Logical operators Nullish coalescing operator '??' Loops: while and for The "switch" statement Functions Function expressions Arrow functions, the basics JavaScript specials Code quality Debugging in the browser Coding Style Comments Ninja code Automated testing with Mocha Polyfills and transpilers Objects: the basics Objects Object references and copying Garbage collection Object methods, "this" Constructor, operator "new" Optional chaining '?.' Symbol type Object to primitive conversion Data types Methods of primitives Numbers Strings Arrays Array methods Iterables Map and Set WeakMap and WeakSet Object.keys, values, entries Destructuring assignment Date and time JSON methods, toJSON Advanced working with functions Recursion and stack Rest parameters and spread syntax Variable scope, closure The old "var" Global object Function object, NFE The "new Function" syntax Scheduling: setTimeout and setInterval Decorators and forwarding, call/apply Function binding Arrow functions revisited Object properties configuration Property flags and descriptors Property getters and setters Prototypes, inheritance Prototypal inheritance F.prototype Native prototypes Prototype methods, objects without __proto__ Classes Class basic syntax Class inheritance Static properties and methods Private and protected properties and methods Extending built-in classes Class checking: "instanceof" Mixins Error handling Error handling, "try...catch" Custom errors, extending Error Promises, async/await Introduction: callbacks Promise Promises chaining Error handling with promises Promise API Promisification Microtasks Async/await Generators, advanced iteration Generators Async iteration and generators Modules Modules, introduction Export and Import Dynamic imports Miscellaneous Proxy and Reflect Eval: run a code string Currying Reference Type BigInt Unicode, String internals WeakRef and FinalizationRegistry Browser: Document, Events, Interfaces Learning how to manage the browser page: add elements, manipulate their size and position, dynamically create interfaces and interact with the visitor. Document Browser environment, specs DOM tree Walking the DOM Searching: getElement*, querySelector* Node properties: type, tag and contents Attributes and properties Modifying the document Styles and classes Element size and scrolling Window sizes and scrolling Coordinates Introduction to Events Introduction to browser events Bubbling and capturing Event delegation Browser default actions Dispatching custom events UI Events Mouse events Moving the mouse: mouseover/out, mouseenter/leave Drag'n'Drop with mouse events Pointer events Keyboard: keydown and keyup Scrolling Forms, controls Form properties and methods Focusing: focus/blur Events: change, input, cut, copy, paste Forms: event and method submit Document and resource loading Page: DOMContentLoaded, load, beforeunload, unload Scripts: async, defer Resource loading: onload and onerror Miscellaneous Mutation observer Selection and Range Event loop: microtasks and macrotasks Additional articles List of extra topics that assume you've covered the first two parts of tutorial. There is no clear hierarchy here, you can read articles in the order you want. Frames and windows Popups and window methods Cross-window communication The clickjacking attack Binary data, files ArrayBuffer, binary arrays TextDecoder and TextEncoder Blob File and FileReader Network requests Fetch FormData Fetch: Download progress Fetch: Abort Fetch: Cross-Origin Requests Fetch API URL objects XMLHttpRequest Resumable file upload Long polling WebSocket Server Sent Events Storing data in the browser Cookies, document.cookie LocalStorage, sessionStorage IndexedDB Animation Bezier curve CSS-animations JavaScript animations Web components From the orbital height Custom elements Shadow DOM Template element Shadow DOM slots, composition Shadow DOM styling Shadow DOM and events Regular expressions Patterns and flags Character classes Unicode: flag "u" and class \p{...} Anchors: string start ^ and end $ Multiline mode of anchors ^ $, flag "m" Word boundary: \b Escaping, special characters Sets and ranges [...] Quantifiers +, *, ? and {n} Greedy and lazy quantifiers Capturing groups Backreferences in pattern: \N and \k<name> Alternation (OR) | Lookahead and lookbehind Catastrophic backtracking Sticky flag "y", searching at position Methods of RegExp and String
The Modern JavaScript Tutorial
https://javascript.info/translate
There are following translations (in the alphabetical order): Language Translated (%) Last Commit Published Albanian 11% 23 Jun 2023 Arabic 57% 28 May 2023 https://ar.javascript.info Armenian 12% 11 Jul 2022 Azerbaijani 17% 18 Feb 2023 Bengali 34% 15 Oct 2023 Bosnian 17% 15 Dec 2021 Bulgarian 24% 2 Oct 2023 Burmese 4% 20 Aug 2023 Catalan 32% 15 Dec 2021 Central Khmer 30% 15 Dec 2021 Chinese 92% 14 Oct 2023 https://zh.javascript.info Chinese Traditional 33% 15 Dec 2021 Croatian 1% 22 Aug 2022 Czech 14% 14 Aug 2023 Danish 3% 14 Aug 2023 Dutch 13% 15 Dec 2021 Finnish 5% 19 Apr 2022 French 83% 16 Nov 2023 https://fr.javascript.info Georgian 5% 15 Dec 2021 German 9% 25 Nov 2023 Greek 13% 14 Aug 2023 Hebrew 11% 15 Dec 2021 Hindi 9% 15 Dec 2021 Hungarian 6% 15 Dec 2021 Indonesian 64% 25 Sep 2023 https://id.javascript.info Italian 87% 5 Nov 2023 https://it.javascript.info Japanese 90% 30 Sep 2023 https://ja.javascript.info Kazakh 3% 29 Apr 2023 Korean 74% 25 Nov 2023 https://ko.javascript.info Kyrgyz 9% 18 May 2023 Lithuanian 16% 21 Aug 2022 Malay 1% 12 Nov 2022 Malayalam 5% 14 Feb 2022 Montenegrin 25% 15 Dec 2021 Norvegian 32% 15 Dec 2021 Persian (Farsi) 65% 14 Nov 2023 https://fa.javascript.info Polish 25% 22 Oct 2022 Portuguese 10% 18 Sep 2023 Punjabi 17% 15 Dec 2021 Romanian 26% 6 Sep 2023 Russian 91% 24 Nov 2023 https://learn.javascript.ru Serbian 5% 15 Dec 2021 Sinhala 11% 15 Dec 2021 Slovak 11% 15 Dec 2021 Slovenian 5% 15 Dec 2021 Spanish 91% 19 Nov 2023 https://es.javascript.info Tamil 6% 15 Dec 2021 Telugu 3% 12 Feb 2022 Thai 17% 12 Jun 2023 Turkish 63% 12 Oct 2023 https://tr.javascript.info Turkmen 11% 15 Dec 2021 Ukrainian 89% 30 Oct 2023 https://uk.javascript.info Urdu 4% 20 Feb 2023 Uyghur 1% 10 Apr 2023 Uzbek 51% 15 Dec 2021 Vietnamese 15% 24 Jul 2023 Help us to translate: click the language name link above, it leads to the repo. Then read the instruction. That's simple, join in! Help to translate To participate in a translation, simply choose the language in the list above. Then you’ll get to the language page and see instructions. Maybe even in that language, if the readme is translated :) Becoming a maintainer Anyone can contribute to a translation. But maintainers are the ones who also watch over its quality. Maintainers have the power to review and merge pull requests of others. Please file an issue, if: You’re already a maintainer of a translation, and would like to add another one. You’re interested in becoming a maintainer for a translation, and other maintainers agree to add you. An existing translation is stalled, previous maintainers don’t respond, and you want to take it over. Starting a new translation Your language is not in the list? If you’d like to create a new translation, file an issue with the following information: Language code List of maintainers (one or more): github nick and email As a maintainer, you should know JavaScript well enough to translate and review pull requests of others. We will: Create a new repository for you at javascript-tutorial/{lang-code}.javascript.info. Add/invite all maintainers to the team translate-{lang-code} in the javascript-tutorial organization. Create an special issue in the new repository to track your translation progress. You’ll get an email invite to join (unless you’re a member already). Please accept this invite, so you can get admin access to your repository! You’ll find more translation tips in Readme when the repository is created. Happy translating! Publishing When the translation is at least half-finished, please create an issue with a request to publish. Your name and contributions will show up at the About page.
Translation of the Modern JavaScript Tutorial
https://javascript.info/modules-intro
As our application grows bigger, we want to split it into multiple files, so called “modules”. A module may contain a class or a library of functions for a specific purpose. For a long time, JavaScript existed without a language-level module syntax. That wasn’t a problem, because initially scripts were small and simple, so there was no need. But eventually scripts became more and more complex, so the community invented a variety of ways to organize code into modules, special libraries to load modules on demand. To name some (for historical reasons): AMD – one of the most ancient module systems, initially implemented by the library require.js. CommonJS – the module system created for Node.js server. UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS. Now these all slowly became a part of history, but we still can find them in old scripts. The language-level module system appeared in the standard in 2015, gradually evolved since then, and is now supported by all major browsers and in Node.js. So we’ll study the modern JavaScript modules from now on. What is a module? A module is just a file. One script is one module. As simple as that. Modules can load each other and use special directives export and import to interchange functionality, call functions of one module from another one: export keyword labels variables and functions that should be accessible from outside the current module. import allows the import of functionality from other modules. For instance, if we have a file sayHi.js exporting a function: // 📁 sayHi.js export function sayHi(user) { alert(`Hello, ${user}!`); } …Then another file may import and use it: // 📁 main.js import {sayHi} from './sayHi.js'; alert(sayHi); // function... sayHi('John'); // Hello, John! The import directive loads the module by path ./sayHi.js relative to the current file, and assigns exported function sayHi to the corresponding variable. Let’s run the example in-browser. As modules support special keywords and features, we must tell the browser that a script should be treated as a module, by using the attribute <script type="module">. Like this: Resultsay.jsindex.html <!doctype html> <script type="module"> import {sayHi} from './say.js'; document.body.innerHTML = sayHi('John'); </script> The browser automatically fetches and evaluates the imported module (and its imports if needed), and then runs the script. Modules work only via HTTP(s), not locally If you try to open a web-page locally, via file:// protocol, you’ll find that import/export directives don’t work. Use a local web-server, such as static-server or use the “live server” capability of your editor, such as VS Code Live Server Extension to test modules. Core module features What’s different in modules, compared to “regular” scripts? There are core features, valid both for browser and server-side JavaScript. Always “use strict” Modules always work in strict mode. E.g. assigning to an undeclared variable will give an error. <script type="module"> a = 5; // error </script> Module-level scope Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts. In the example below, two scripts are imported, and hello.js tries to use user variable declared in user.js. It fails, because it’s a separate module (you’ll see the error in the console): Resulthello.jsuser.jsindex.html <!doctype html> <script type="module" src="user.js"></script> <script type="module" src="hello.js"></script> Modules should export what they want to be accessible from outside and import what they need. user.js should export the user variable. hello.js should import it from user.js module. In other words, with modules we use import/export instead of relying on global variables. This is the correct variant: Resulthello.jsuser.jsindex.html import {user} from './user.js'; document.body.innerHTML = user; // John In the browser, if we talk about HTML pages, independent top-level scope also exists for each <script type="module">. Here are two scripts on the same page, both type="module". They don’t see each other’s top-level variables: <script type="module"> // The variable is only visible in this module script let user = "John"; </script> <script type="module"> alert(user); // Error: user is not defined </script> Please note: In the browser, we can make a variable window-level global by explicitly assigning it to a window property, e.g. window.user = "John". Then all scripts will see it, both with type="module" and without it. That said, making such global variables is frowned upon. Please try to avoid them. A module code is evaluated only the first time when imported If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers. The one-time evaluation has important consequences, that we should be aware of. Let’s see a couple of examples. First, if executing a module code brings side-effects, like showing a message, then importing it multiple times will trigger it only once – the first time: // 📁 alert.js alert("Module is evaluated!"); // Import the same module from different files // 📁 1.js import `./alert.js`; // Module is evaluated! // 📁 2.js import `./alert.js`; // (shows nothing) The second import shows nothing, because the module has already been evaluated. There’s a rule: top-level module code should be used for initialization, creation of module-specific internal data structures. If we need to make something callable multiple times – we should export it as a function, like we did with sayHi above. Now, let’s consider a deeper example. Let’s say, a module exports an object: // 📁 admin.js export let admin = { name: "John" }; If this module is imported from multiple files, the module is only evaluated the first time, admin object is created, and then passed to all further importers. All importers get exactly the one and only admin object: // 📁 1.js import {admin} from './admin.js'; admin.name = "Pete"; // 📁 2.js import {admin} from './admin.js'; alert(admin.name); // Pete // Both 1.js and 2.js reference the same admin object // Changes made in 1.js are visible in 2.js As you can see, when 1.js changes the name property in the imported admin, then 2.js can see the new admin.name. That’s exactly because the module is executed only once. Exports are generated, and then they are shared between importers, so if something changes the admin object, other importers will see that. Such behavior is actually very convenient, because it allows us to configure modules. In other words, a module can provide a generic functionality that needs a setup. E.g. authentication needs credentials. Then it can export a configuration object expecting the outer code to assign to it. Here’s the classical pattern: A module exports some means of configuration, e.g. a configuration object. On the first import we initialize it, write to its properties. The top-level application script may do that. Further imports use the module. For instance, the admin.js module may provide certain functionality (e.g. authentication), but expect the credentials to come into the config object from outside: // 📁 admin.js export let config = { }; export function sayHi() { alert(`Ready to serve, ${config.user}!`); } Here, admin.js exports the config object (initially empty, but may have default properties too). Then in init.js, the first script of our app, we import config from it and set config.user: // 📁 init.js import {config} from './admin.js'; config.user = "Pete"; …Now the module admin.js is configured. Further importers can call it, and it correctly shows the current user: // 📁 another.js import {sayHi} from './admin.js'; sayHi(); // Ready to serve, Pete! import.meta The object import.meta contains the information about the current module. Its content depends on the environment. In the browser, it contains the URL of the script, or a current webpage URL if inside HTML: <script type="module"> alert(import.meta.url); // script URL // for an inline script - the URL of the current HTML-page </script> In a module, “this” is undefined That’s kind of a minor feature, but for completeness we should mention it. In a module, top-level this is undefined. Compare it to non-module scripts, where this is a global object: <script> alert(this); // window </script> <script type="module"> alert(this); // undefined </script> Browser-specific features There are also several browser-specific differences of scripts with type="module" compared to regular ones. You may want to skip this section for now if you’re reading for the first time, or if you don’t use JavaScript in a browser. Module scripts are deferred Module scripts are always deferred, same effect as defer attribute (described in the chapter Scripts: async, defer), for both external and inline scripts. In other words: downloading external module scripts <script type="module" src="..."> doesn’t block HTML processing, they load in parallel with other resources. module scripts wait until the HTML document is fully ready (even if they are tiny and load faster than HTML), and then run. relative order of scripts is maintained: scripts that go first in the document, execute first. As a side effect, module scripts always “see” the fully loaded HTML-page, including HTML elements below them. For instance: <script type="module"> alert(typeof button); // object: the script can 'see' the button below // as modules are deferred, the script runs after the whole page is loaded </script> Compare to regular script below: <script> alert(typeof button); // button is undefined, the script can't see elements below // regular scripts run immediately, before the rest of the page is processed </script> <button id="button">Button</button> Please note: the second script actually runs before the first! So we’ll see undefined first, and then object. That’s because modules are deferred, so we wait for the document to be processed. The regular script runs immediately, so we see its output first. When using modules, we should be aware that the HTML page shows up as it loads, and JavaScript modules run after that, so the user may see the page before the JavaScript application is ready. Some functionality may not work yet. We should put “loading indicators”, or otherwise ensure that the visitor won’t be confused by that. Async works on inline scripts For non-module scripts, the async attribute only works on external scripts. Async scripts run immediately when ready, independently of other scripts or the HTML document. For module scripts, it works on inline scripts as well. For example, the inline script below has async, so it doesn’t wait for anything. It performs the import (fetches ./analytics.js) and runs when ready, even if the HTML document is not finished yet, or if other scripts are still pending. That’s good for functionality that doesn’t depend on anything, like counters, ads, document-level event listeners. <!-- all dependencies are fetched (analytics.js), and the script runs --> <!-- doesn't wait for the document or other <script> tags --> <script async type="module"> import {counter} from './analytics.js'; counter.count(); </script> External scripts External scripts that have type="module" are different in two aspects: External scripts with the same src run only once: <!-- the script my.js is fetched and executed only once --> <script type="module" src="my.js"></script> <script type="module" src="my.js"></script> External scripts that are fetched from another origin (e.g. another site) require CORS headers, as described in the chapter Fetch: Cross-Origin Requests. In other words, if a module script is fetched from another origin, the remote server must supply a header Access-Control-Allow-Origin allowing the fetch. <!-- another-site.com must supply Access-Control-Allow-Origin --> <!-- otherwise, the script won't execute --> <script type="module" src="http://another-site.com/their.js"></script> That ensures better security by default. No “bare” modules allowed In the browser, import must get either a relative or absolute URL. Modules without any path are called “bare” modules. Such modules are not allowed in import. For instance, this import is invalid: import {sayHi} from 'sayHi'; // Error, "bare" module // the module must have a path, e.g. './sayHi.js' or wherever the module is Certain environments, like Node.js or bundle tools allow bare modules, without any path, as they have their own ways for finding modules and hooks to fine-tune them. But browsers do not support bare modules yet. Compatibility, “nomodule” Old browsers do not understand type="module". Scripts of an unknown type are just ignored. For them, it’s possible to provide a fallback using the nomodule attribute: <script type="module"> alert("Runs in modern browsers"); </script> <script nomodule> alert("Modern browsers know both type=module and nomodule, so skip this") alert("Old browsers ignore script with unknown type=module, but execute this."); </script> Build tools In real-life, browser modules are rarely used in their “raw” form. Usually, we bundle them together with a special tool such as Webpack and deploy to the production server. One of the benefits of using bundlers – they give more control over how modules are resolved, allowing bare modules and much more, like CSS/HTML modules. Build tools do the following: Take a “main” module, the one intended to be put in <script type="module"> in HTML. Analyze its dependencies: imports and then imports of imports etc. Build a single file with all modules (or multiple files, that’s tunable), replacing native import calls with bundler functions, so that it works. “Special” module types like HTML/CSS modules are also supported. In the process, other transformations and optimizations may be applied: Unreachable code removed. Unused exports removed (“tree-shaking”). Development-specific statements like console and debugger removed. Modern, bleeding-edge JavaScript syntax may be transformed to older one with similar functionality using Babel. The resulting file is minified (spaces removed, variables replaced with shorter names, etc). If we use bundle tools, then as scripts are bundled together into a single file (or few files), import/export statements inside those scripts are replaced by special bundler functions. So the resulting “bundled” script does not contain any import/export, it doesn’t require type="module", and we can put it into a regular script: <!-- Assuming we got bundle.js from a tool like Webpack --> <script src="bundle.js"></script> That said, native modules are also usable. So we won’t be using Webpack here: you can configure it later. Summary To summarize, the core concepts are: A module is a file. To make import/export work, browsers need <script type="module">. Modules have several differences: Deferred by default. Async works on inline scripts. To load external scripts from another origin (domain/protocol/port), CORS headers are needed. Duplicate external scripts are ignored. Modules have their own, local top-level scope and interchange functionality via import/export. Modules always use strict. Module code is executed only once. Exports are created once and shared between importers. When we use modules, each module implements the functionality and exports it. Then we use import to directly import it where it’s needed. The browser loads and evaluates the scripts automatically. In production, people often use bundlers such as Webpack to bundle modules together for performance and other reasons. In the next chapter we’ll see more examples of modules, and how things can be exported/imported.
Modules, introduction
https://nitro.unjs.io/guide/community/contributing/
Contributing Thank you for wanting to contribute to Nitro 💛 Before everything, please make sure to check the open issues or the discussions. To contribute locally: Fork and clone unjs/nitro Enable corepack using corepack enable (use npm i -g corepack for Node.js < 16.10) Install dependencies using pnpm install Activate passive watcher using pnpm stub Start playground with pnpm dev and open http://localhost:3000 You can also try examples/ using pnpm nitro dev examples/<name> and pnpm nitro build examples/<name> Make changes Ensure all tests pass using the pnpm test command Open a Pull-Request You can also run pnpm vitest test/presets/node.test.ts to run a single test. Edit this page on GitHub Guide TypeScript Overview
Contributing · Nitro
https://nitro.unjs.io/guide/typescript/
TypeScript Support Nitro supports TypeScript by default. If you are using the starter template, you have nothing to do ✨. To add type hints within your project, create a tsconfig.json file: tsconfig.json { "extends": "./.nitro/types/tsconfig.json" } Copy to clipboard Run npx nitropack prepare to generate the types for global auto-imports. This can be useful in a CI environment or as a postinstall command in your package.json. If you are using Nuxt, your tsconfig.json can stay: tsconfig.json { "extends": "./.nuxt/tsconfig.json" } Copy to clipboard Edit this page on GitHub Guide Plugins Community Contributing
TypeScript · Nitro
https://nitro.unjs.io/guide/plugins/
Plugins Use plugins to extend Nitro's runtime behavior. Plugins are auto-registered (filename ordering) and run synchronously on the first nitro initialization. They receive nitroApp context, which can be used to hook into lifecycle events. Scanning pattern: plugins/**/*.{ts,mjs,js,cjs} You can order the plugins by prefixing them with a number: plugins/ 1.first.ts 2.second.ts Copy to clipboard Example: Simple plugin // plugins/test.ts export default defineNitroPlugin((nitroApp) => { console.log('Nitro plugin', nitroApp) }) Copy to clipboard If you have plugins in another directory, you can use the plugins option: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ plugins: ['my-plugins/hello.ts'] }) Copy to clipboard Nitro Runtime Hooks Hooks allow extending the default runtime behaviour of Nitro by registering custom functions to the lifecycle events within plugins. (Read unjs/hookable to see how it works.) Example: export default defineNitroPlugin((nitro) => { nitro.hooks.hook("close", async () => { // Will run when nitro is being closed }); }) Copy to clipboard Available Hooks See the source code for list of all available runtime hooks. "close", () => {} "error", (error, { event? }) => {} "render:response", (response, { event }) => {} "request", (event) => {} "beforeResponse", (event, { body }) => {} "afterResponse", (event, { body }) => {} Examples Capturing Errors You can use plugins to capture all application errors. export default defineNitroPlugin((nitro) => { nitro.hooks.hook("error", async (error, { event }) => { console.error(`${event.path} Application error:`, error) }); }) Copy to clipboard Graceful Shutdown You can use plugins to register a hook that resolves when Nitro is closed. export default defineNitroPlugin((nitro) => { nitro.hooks.hookOnce("close", async () => { // Will run when nitro is closed console.log("Closing nitro server...") await new Promise((resolve) => setTimeout(resolve, 500)); console.log("Task is done!"); }); }) Copy to clipboard Request and Response lifecycle You can use plugins to register a hook that can run on request lifecycle: export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook("request", (event) => { console.log("on request", event.path); }); nitroApp.hooks.hook("beforeResponse", (event, { body }) => { console.log("on response", event.path, { body }); }); nitroApp.hooks.hook("afterResponse", (event, { body }) => { console.log("on after response", event.path, { body }); }); }); Copy to clipboard Renderer Response You can use plugins to register a hook that modifies the renderer response. This only works for render handler defined with renderer and won't be called for other api/server routes. In Nuxt this hook will be called for Server Side Rendered pages export default defineNitroPlugin((nitro) => { nitro.hooks.hook('render:response', (response, { event }) => { // Inspect or Modify the renderer response here console.log(response) }) }) Copy to clipboard Edit this page on GitHub Guide Utils Guide TypeScript
Plugins · Nitro
https://nitro.unjs.io/guide/utils/
Utils Nitro helps you to stay organized allowing you to take advantage of the auto-imports feature. Every export in the utils directory and its subdirectories will become available globally in your application. Example: Create a utils/sum.ts file where a function useSum is exported: utils/sum.ts export function useSum(a: number, b: number) { return a + b } Copy to clipboard Use it in your routes/index.ts file without importing it: routes/index.ts export default defineEventHandler(() => { const sum = useSum(1, 2) // auto-imported return { sum } }) Copy to clipboard Experimental Composition API Nitro (2.6+) enables a new server development experience in order to split application logic into smaller "composable" utilities that are fully decoupled from each other and can directly assess to a shared context (request event) without needing it to be passed along. This pattern is inspired from Vue Composition API and powered by unjs/unctx. This feature is currently supported for Node.js and Bun runtimes and also coming soon to other presets that support AsyncLocalStorage interface. In order to enable composition API, you have to enable asyncContext flag: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ experimental: { asyncContext: true } }); Copy to clipboard After enabling this flag, you can use useEvent() (auto imported) in any utility or composable to access the request event without manually passing it along: with async context without async context // routes/index.ts export default defineEventHandler(async () => { const user = await useAuth() }) // utils/auth.ts export function useAuth() { return useSession(useEvent()) } Copy to clipboard Edit this page on GitHub Guide Assets Guide Plugins
Utils · Nitro
https://nitro.unjs.io/guide/assets/
Assets Handling Nitro handles assets via the public/ directory. Public Assets All assets in public/ directory will be automatically served. public/ image.png <-- /image.png video.mp4 <-- /video.mp4 robots.txt <-- /robots.txt package.json nitro.config.ts Copy to clipboard When building with Nitro, it will copy the public/ directory to .output/public/ and create a manifest with metadata: { "/image.png": { "type": "image/png", "etag": "\"4a0c-6utWq0Kbk5OqDmksYCa9XV8irnM\"", "mtime": "2023-03-04T21:39:45.086Z", "size": 18956 }, "/robots.txt": { "type": "text/plain; charset=utf-8", "etag": "\"8-hMqyDrA8fJ0R904zgEPs3L55Jls\"", "mtime": "2023-03-04T21:39:45.086Z", "size": 8 }, "/video.mp4": { "type": "video/mp4", "etag": "\"9b943-4UwfQXKUjPCesGPr6J5j7GzNYGU\"", "mtime": "2023-03-04T21:39:45.085Z", "size": 637251 } } Copy to clipboard This allows Nitro to know the public assets without scanning the directory, giving high performance with caching headers. Server Assets All assets in assets/ directory will be added to the server bundle. They can be addressed by the assets:server mount point using useStorage('assets:server') Keys can be written assets/server/my_file_path or assets:server:my_file_path. Custom Server Assets In order to add assets from a custom directory, path will need to be defined in the nitro config: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ serverAssets: [{ baseName: 'my_directory', dir: './server/my_directory' }] }) Copy to clipboard They can be addressed by the key assets/my_directory/. Examples Example: Retrieving a json data from default assets directory: export default defineEventHandler(async () => { const data = await useStorage().getItem(`assets/server/data.json`) return data }) Copy to clipboard Example: Retrieving a html file from a custom assets directory: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ serverAssets: [{ baseName: 'templates', dir: './templates' // Relative to `srcDir` (`server/` for nuxt) }] }) Copy to clipboard // routes/success.ts export default defineEventHandler(async (event) => { return await useStorage().getItem(`assets/templates/success.html`) // or return await useStorage('assets:templates').getItem(`success.html`) }) Copy to clipboard Edit this page on GitHub Guide Cache API Guide Utils
Assets · Nitro
https://nitro.unjs.io/guide/cache/
Cache API Nitro provides a powerful caching system built on top of the storage layer. It stores the data in the cache mountpoint. In development, it will use the FS driver writting to .nitro/cache or .nuxt/cache if using Nuxt. In production, it will use the memory driver by default. To overwrite the production storage, set the cache mountpoint using the storage option: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ storage: { cache: { driver: 'redis', /* redis connector options */ } } }) Copy to clipboard To overwrite the cache mountpoint in development, use the devStorage option to add the cache mountpoint. Usage Router Handler Function // Cache an API handler export default cachedEventHandler((event) => { // My event handler }, options); Copy to clipboard Examples If you come from Nuxt, all the examples below should be placed inside the server/ directory. Route Handler Cache a route with stale-while-revalidate behavior for 10 second: routes/cached.ts export default cachedEventHandler(async () => { return `Response generated at ${new Date().toISOString()}`; }, { maxAge: 10 }); Copy to clipboard The response will be cached for 10 seconds and a stale value will be sent to the client while the cache is being updated in the background. If you want to immediately return the updated response set swr: false. The cached answer will be store in development inside .nitro/cache/handlers/_/*.json. By default, all incoming request headers are dropped when handling cached responses. If you define the varies option, only the specified headers will be considered when caching and serving the responses. Function Cache for 1 hour the result of a function fetching the GitHub stars for a repository: utils/github.ts api/stars/[...repo export const cachedGHStars = cachedFunction(async (repo: string) => { const data: any = await $fetch(`https://api.github.com/repos/${repo}`) return data.stargazers_count }, { maxAge: 60 * 60, name: 'ghStars', getKey: (repo: string) => repo }) Copy to clipboard The stars will be cached in development inside .nitro/cache/functions/ghStars/<owner>/<repo>.json with value being the number of stars. {"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"} Copy to clipboard Route Rules This feature enables you to add caching routes based on a glob pattern directly in the main configuration file. This feature is still experimental and may evolve in the future. Cache all the blog routes for 1 hour with stale-while-revalidate behavior: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ routeRules: { "/blog/**": { swr: 60 * 60, // or cache: { maxAge: 60 * 60 } }, }, }); Copy to clipboard If we want to use a custom storage mountpoint, we can use the base option. Let's store our cache result for the blog routes in a Redis storage for production: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ storage: { redis: { driver: "redis", url: "redis://localhost:6379", }, }, routeRules: { "/blog/**": { swr: 60 * 60, cache: { base: "redis", }, }, }, }); Copy to clipboard Options The cachedEventHandler and cachedFunction functions accept the following options: name: Handler name. Type: String Default: Guessed from function name if not provided and fallback to _ otherwise. group: Part of cache name. Useful to organize cache storage. Type: String Default: 'nitro/handlers' for handlers and 'nitro/functions' for functions. getKey: A function that accepts the same arguments of the function and returns a cache key (String). Type: Function Default: If not provided, a built-in hash function will be used. integrity: A value that invalidates the cache when changed. Type: String Default: Computed from function code, used in development to invalidate the cache when the function code changes. maxAge: Maximum age that cache is valid in seconds. Type: Number Default: 1 (second). staleMaxAge: Maximum age that a stale cache is valid in seconds. If set to -1 a stale value will still be sent to the client, while updating the cache in the background. Type: Number Default: 0 (disabled). swr: Enable stale-while-revalidate behavior. Default: true base: Name of the storage mountpoint to use for caching. Default: cache. shouldInvalidateCache: A function that returns a Boolean to invalidate the current cache and create a new one. Type: Function shouldBypassCache: A function that returns a boolean to bypass the current cache without invalidating the existing entry. Type: Function varies: An array of request headers to be considered for the cache Type: string[] Edit this page on GitHub Guide Storage Layer Guide Assets
Cache API · Nitro
https://nitro.unjs.io/guide/storage/
Storage Layer Nitro provides a built-in storage layer that can abstract filesystem or database or any other data source. useStorage() is an instance of createStorage using the memory driver. Example: Simple (in memory) operations await useStorage().setItem('test:foo', { hello: 'world' }) await useStorage().getItem('test:foo') // You can also specify the base in useStorage(base) await useStorage('test').setItem('foo', { hello: 'world' }) await useStorage('test').getItem('foo') Copy to clipboard See Unstorage for detailed usage. Mountpoints You can mount storage drivers using the storage option: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ storage: { 'redis': { driver: 'redis', /* redis connector options */ }, 'db': { driver: 'fs', base: './data/db' } } }) Copy to clipboard Runtime configuration In scenarios where the mount point configuration is not known until runtime, Nitro can dynamically add mount points during startup using plugins: This is a temporary workaround, with a better solution coming in the future! Keep a lookout on the GitHub issue here. plugins/storage.ts nitro.config.ts nuxt.config.ts import redisDriver from 'unstorage/drivers/redis' export default defineNitroPlugin(() => { const storage = useStorage() // Dynamically pass in credentials from runtime configuration, or other sources const driver = redisDriver({ base: 'redis', host: useRuntimeConfig().redis.host, port: useRuntimeConfig().redis.port, /* other redis connector options */ }) // Mount driver storage.mount('redis', driver) }) Copy to clipboard Usage: await useStorage('redis').setItem('foo', { hello: 'world' }) await useStorage('redis').getItem('foo') // or await useStorage().setItem('redis:foo', { hello: 'world' }) await useStorage().getItem('redis:foo') Copy to clipboard Usage with generics: await useStorage().getItem<string>('foo') // => string await useStorage<string>().getItem('foo') // => string await useStorage<string>().setItem('foo', 123) // ts error type Foo = { data: number } await useStorage().getItem<Foo>('foo') // => Foo Copy to clipboard You can find the list of drivers on unstorage documentation. In development, Nitro adds the cache mountpoint using the FS driver writting to .nitro/cache or .nuxt/cache if using Nuxt. await useStorage('cache').setItem('foo', { hello: 'world' }) await useStorage('cache').getItem('foo') Copy to clipboard Development storage You can use the devStorage key to overwrite the storage configuration during development, very useful when you use a database in production and want to use the filesystem in development. nitro.config.ts nuxt.config.ts export default defineNitroConfig({ // Production storage: { db: { driver: 'redis', /* redis connector options */ } }, // Development devStorage: { db: { driver: 'fs', base: './data/db' } } }) Copy to clipboard Edit this page on GitHub Guide Routing Guide Cache API
Storage Layer · Nitro
https://nitro.unjs.io/guide/routing/
Routing Nitro support filesystem routing as well as defining route rules for maximum flexibility and performance. Filesystem Routing Nitro supports file-based routing for your API routes. Handler files inside api/ and routes/ directory will be automatically mapped to unjs/h3 routes. api/ test.ts <-- /api/test routes/ hello.ts <-- /hello nitro.config.ts Copy to clipboard Some providers like Vercel use a top-level api/ directory as a feature, therefore routes placed in /api wont work. You will have to use routes/api/. If you are using Nuxt, move the api/ and routes/ inside the server/ directory. Simple route // api/hello.ts export default defineEventHandler(() => { return { hello: 'world' } }) Copy to clipboard You can now universally call this API using await $fetch('/api/hello'). Route with params // routes/hello/[name].ts export default defineEventHandler(event => `Hello ${event.context.params.name}!`) Copy to clipboard /hello/nitro Hello nitro! Copy to clipboard To include the /, use [...name].ts: // routes/hello/[...name].ts export default defineEventHandler(event => `Hello ${event.context.params.name}!`) Copy to clipboard /hello/nitro/is/hot Hello nitro/is/hot! Copy to clipboard Specific request method API route with a specific HTTP request method (get, post, put, delete, options and so on). GET POST // routes/users/[id].get.ts export default defineEventHandler(async (event) => { const { id } = event.context.params // TODO: fetch user by id return `User profile!` }) Copy to clipboard Check out h3 JSDocs for all available utilities like readBody. Catch all route // routes/[...].ts export default defineEventHandler(event => `Default page`) Copy to clipboard Route Rules Nitro allows you to add logic at the top-level of your configuration, useful for redirecting, proxying, caching and adding headers to routes. It is a map from route pattern (following unjs/radix3) to route options. When cache option is set, handlers matching pattern will be automatically wrapped with defineCachedEventHandler. See the Cache API for all available cache options. swr: true|number is shortcut for cache: { swr: true, maxAge: number } Example: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ routeRules: { '/blog/**': { swr: true }, '/blog/**': { swr: 600 }, '/blog/**': { static: true }, '/blog/**': { cache: { /* cache options*/ } }, '/assets/**': { headers: { 'cache-control': 's-maxage=0' } }, '/api/v1/**': { cors: true, headers: { 'access-control-allow-methods': 'GET' } }, '/old-page': { redirect: '/new-page' }, '/proxy/example': { proxy: 'https://example.com' }, '/proxy/**': { proxy: '/api/**' }, } }) Copy to clipboard Route Middleware Nitro route middleware can hook into the request lifecycle. A middleware can modify the request before it is processed, not after. Middleware are auto-registered within the middleware/ directory. routes/ hello.ts middleware/ auth.ts logger.ts ... nitro.config.ts Copy to clipboard Simple Middleware Middleware are defined exactly like route handlers with the only exception that they should not return anything. Returning from middleware behaves like returning from a request - the value will be returned as a response and further code will not be ran. middleware/auth.ts export default defineEventHandler((event) => { // Extends or modify the event event.context.user = { name: 'Nitro' } }) Copy to clipboard Returning anything from a middleware will close the request and should be avoided! Any returned value from middleware will be the response and further code will not be executed however this is not recommended to do! Execution Order Middleware are executed in directory listing order. middleware/ auth.ts <-- First logger.ts <-- Second ... <-- Third Copy to clipboard Prefix middleware with a number to control their execution order. middleware/ 1.logger.ts <-- First 2.auth.ts <-- Second 3.... <-- Third Copy to clipboard Request Filtering Middleware are executed on every request. Apply custom logic to scope them to specific conditions. For example, you can use the URL to apply a middleware to a specific route: middleware/auth.ts export default defineEventHandler((event) => { // Will only execute for /auth route if (getRequestURL(event).startsWith('/auth')) { event.context.user = { name: 'Nitro' } } }) Copy to clipboard Edit this page on GitHub Guide Auto Imports Guide Storage Layer
Routing · Nitro
https://nitro.unjs.io/guide/configuration/
Configuration You can customize your Nitro server with single configuration file: nitro.config.ts. All deployment providers are built on the same options API. If you are using Nuxt, use the nitro option in your Nuxt config. nitro.config.ts nuxt.config.ts export default defineNitroConfig({ // Nitro options }) Copy to clipboard Read all the available options to configure Nitro. Nitro loads the configuration using unjs/c12, giving more possibilities such as using .nitrorc. .nitrorc .nuxtrc timing=true Copy to clipboard Runtime Configuration Nitro provides a runtime config API to expose configuration within your application, with the ability to update it at runtime by setting environment variables. To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your configuration file. Example: nitro.config.ts nuxt.config.ts export default defineNitroConfig({ runtimeConfig: { helloThere: "foobar", } }) Copy to clipboard You can now access the runtime config using useRuntimeConfig(event). Example: api/example.get.ts (nitro) server/api/example.get.ts (nuxt) export default defineEventHandler((event) => { return useRuntimeConfig(event).helloThere // foobar }); Copy to clipboard Note: Consider using useRuntimeConfig(event) within event handlers and utilities and avoid calling it in ambient global contexts. Environment Variables Nitro supports defining environment variables using .env file in development (use platform variables for production). Create an .env file in your project root: .env TEST="123" Copy to clipboard You can universally access environment variables using import.meta.env.TEST or process.env.TEST. Note: Consider writing any logic that depends on environment variables within event handlers and utilities and avoid accessing and caching them in ambient global contexts. Update runtime config using environment variables The variables prefixed with NITRO_ will be applied to runtime config, and they will override the variables defined within your nitro.config.ts file. (matching "camelCase" version). Example: .env (nitro) .env (nuxt) NITRO_HELLO_THERE="123" Copy to clipboard Edit this page on GitHub Guide Getting Started Guide Auto Imports
Configuration · Nitro
https://nitro.unjs.io/guide/auto-imports/
Auto Imports Nitro is using unjs/unimport to auto import utilities when used with full tree-shaking support. Available Auto Imports defineCachedFunction(fn, options) / cachedFunction(fn, options) defineCachedEventHandler(handler, options) / cachedEventHandler(handler, options) defineRenderHandler(handler) useRuntimeConfig(event?) useAppConfig(event?) useStorage(base?) useNitroApp() defineNitroPlugin(plugin) nitroPlugin(plugin) getRouteRules(event) Check the source code for list of available auto imports. With TypeScript enabled, you can easily see them as global utilities in your IDE. The types are auto generated for global auto-imports when running the prepare or dev command. Manual Imports For some edge cases (IDE support and libraries in node_modules) it is impossible to rely on auto imports. You can import them from virtual #imports file. It will be still tree-shaken: plugins/test.ts import { useStorage } from '#imports' Copy to clipboard Edit this page on GitHub Guide Configuration Guide Routing
Auto Imports · Nitro
https://nitro.unjs.io/guide/getting-started/
Getting Started Let's create a new Nitro app in few steps. Play Online Open on Stackblitz Open on CodeSandbox Starter Template Make sure you have installed the recommended setup: Create a new project using starter template: npx pnpm bun npx giget@latest nitro nitro-app Copy to clipboard cd nitro-app Copy to clipboard Install the dependencies: npm yarn pnpm bun npm install Copy to clipboard Start the development server: npm run dev Copy to clipboard 🪄 Your API is ready at http://localhost:3000/ Check .nitro/dev/index.mjs if want to know what is happening Build your production-ready server: npm run build Copy to clipboard Output is in the .output directory and ready to be deployed on almost any provider with no dependencies. You can try it locally with: npm run preview Copy to clipboard Nightly Release Channel Nitro offers a nightly release channel that automatically releases for every commit to main branch. You can opt-in to the nightly release channel by updating your package.json: Nitro Nuxt { "devDependencies": { -- "nitropack": "^2.0.0" ++ "nitropack": "npm:nitropack-nightly@latest" } } Copy to clipboard If you are using Nuxt, use the Nuxt nightly channel as it already includes nitropack-nightly. Remove the lockfile (package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb) and reinstall the dependencies. Edit this page on GitHub Guide Configuration
Getting Started · Nitro
https://image.nuxt.com/providers/twicpics
Providers Twicpics Source Nuxt Image internally use Twicpics as static provider. Integration between Twicpics and the image module. What is TwicPics? Twicpics is a Responsive Image Service Solution (SaaS) that enables on-demand responsive image generation. Using the TwicPics Provider you can, out of the box, benefit from at least : performance of our network: global CDN, optimized protocols and competitive caching ideal compression: modern technology and Next-Gen formats (TwicPics delivers WebP natively for accounting browsers and can also delivers avif) And using the TwicPics API, you will be able to access all these features: smart cropping with TwicPics focus auto, true color, flip, turn, crop, zoom. Requirement The only requirement is to have a TwicPics account. If you don't already have one, you can easily create your own TwicPics account for free. Setup You just need to configure the TwicPics provider with the baseURL set to your TwicPics Domain. nuxt.config.ts export default defineNuxtConfig({ image: { twicpics: { baseURL: 'https://<your-twicpics-domain>/' // Feel free to use our demo domain to try the following examples. // baseUrl: 'https://demo.twic.pics/' } } }) Standard properties TwicPics Provider complies with the documentation of nuxt-img and nuxt-picture. fit fit determines how the image is resized in relation to the parameters height and width. TwicPics Provider supports all the the standard values for fit property of Nuxt image and Nuxt picture. Syntax: fit='__cover__' (default value) This will return a variant of your master image cropped to 300x300 while preserving aspect ratio. <NuxtImg provider="twicpics" src="/football.jpg" height=300 width=300 /> This will return a variant of your master image resized to 300x300 with distortion. <NuxtImg provider="twicpics" src="/football.jpg" fit="resize" height=300 width=300 /> This will bring your image back to a 300x600 area with respect to the ratio (1:1) using letterboxing. <NuxtImg provider="twicpics" src="/cat_1x1.jpg" fit="contain" height=600 width=300 /> The letterboxing strips are transparent areas. Feel free to select the color of your choice by using the background property. <NuxtImg provider="twicpics" src="/cat_1x1.jpg" fit="contain" height=600 width=300 background: "red" /> format Specifies the output format. It can be an image format or a preview format. By default, TwicPics will "guess" the best output format for the requesting browser, but you can use format to change this behavior. Syntax: format='avif'|'heif'|'jpeg'|'png'|__'webp'__ WebP is the default format provided by TwicPics (if the browser supports it). Examples: This will return a variant of your image in avif format. <NuxtImg provider="twicpics" src="/cat_1x1.jpg" format="avif" /> This will return a blurry preview of your image in svg format. <NuxtImg provider="twicpics" src="/cat_1x1.jpg" format="preview" /> More informations about format here. quality Specifies the output quality as a number between 1 (poor quality) and 100 (best quality). Syntax: quality=number TwicPics considers quality=70 as default value. NB: TwicPics automatically manages the returned quality according to the network performance for an optimized display speed even in difficult conditions. NB : when Data Saver is activated (android mobile only), default quality=10. Example: <NuxtImg provider="twicpics" src="/cat_1x1.jpg" quality=1 /> More informations about quality here. background background specifies a color that will show through transparent and translucent parts of the image. This will have no effect on images with no transparency nor translucency. Syntax: background=color Example: <NuxtImg provider="twicpics" src="/icon-500.png" background="red" /> <NuxtImg provider="twicpics" src="/cat_1x1.jpg" fit="contain" height=600 width=300 background: 'red' /> More informations about background here. TwicPics modifiers In addition to the standard parameters, the specific features of the TwicPics API are accessible via the modifiers prop of nuxt-img or nuxt-picture. <NuxtImg provider="twicpics" src="/path-to-nuxt-demo.jpg" ... standard props ... :modifiers="{key_1: value_1, ..., key_n: value_n}" /> A complete list of these features and their uses is accessible here. crop crop will extract a zone from the image which size is the given crop size. If no coordinates are given, the focus point will be used as a guide to determine where to start the extraction. If coordinates are given, they will be used to determine the top-left pixel from which to start the extraction and the focus point will be reset to the center of the resulting image. Syntax: { crop: size@coordinates } <NuxtImg provider="twicpics" src="/cat.jpg" :modifiers="{crop:'500x100'}" <!-- no coordinates given --> /> <NuxtImg provider="twicpics" src="/cat.jpg" :modifiers="{crop:'500x100@700x400'}" <!-- passing coordinates --> /> <NuxtImg provider="twicpics" src="/cat.jpg" :modifiers="{focus:'auto', crop:'500x100'}" <!-- using focus auto --> /> More informations about crop here. flip flip will invert the image horizontally, vertically or both depending on the expression provided. Syntax: { flip: 'both' | 'x' | 'y' } <NuxtImg provider="twicpics" src="/puppy.jpg" :modifiers="{flip:'both'}" <!-- horizontal and vertical --> /> <NuxtImg provider="twicpics" src="/puppy.jpg" :modifiers="{flip:'x'}" <!-- horizontal --> /> <NuxtImg provider="twicpics" src="/puppy.jpg" :modifiers="{flip:'y'}" <!-- vertical --> /> More informations about flip here. focus focus will set the focus point coordinates. It doesn't modify the output image in any way but will change the behavior of further transformations that take the focus point into account (namely cover, crop and resize). If auto is used in place of actual coordinates, the focus point will be chosen automagically for you! Syntax: { focus: coordinates|'auto' } <NuxtImg provider="twicpics" src="/cat_1x1.jpg" :modifiers="{focus:'auto', crop:'500x500'}" <!-- using crop with focus auto --> /> <NuxtImg provider="twicpics" src="/football.jpg" :modifiers="{focus:'auto', cover:'1:1'}" <!-- changing ratio with focus auto --> /> <NuxtImg provider="twicpics" src="/path-to-nuxt-demo.jpg" :modifiers="{focus:'200x200', cover:'1:1'}" <!-- changing ratio with selected focus --> /> NB : focus must be placed before the transformations modifying the output image (namely cover, crop and resize). More informations about focus here. truecolor truecolor can be used to prevent color quantization. If no boolean is provided, true is assumed. By default, quantization is allowed (truecolor=false). Quantization occurs whenever the output format is png. Use truecolor if you want to distribute substantially larger but more accurate images with translucency to users on browsers with no WebP support or when png is required as output format. <NuxtImg provider="twicpics" src="/peacock.jpg" format="png" :modifiers="{truecolor:true}" <!-- disallowes color quantization --> /> <NuxtImg provider="twicpics" src="/peacock.jpg" format="png" :modifiers="{truecolor:false}" <!-- allowes color quantization (default value) --> /> More informations about truecolor here. turn turn will change the orientation of the image. It accepts an angle in degrees or an expression. Angles will be rounded to the closest multiple of 90°. Syntax: { turn: number | 'flip' | 'left' | 'right' } <NuxtImg provider="twicpics" src="/football.jpg" :modifiers="{turn:'left'}" <!-- turns image at -90° --> /> <NuxtImg provider="twicpics" src="/football.jpg" :modifiers="{turn:180}" <!-- turns image at 180° --> /> More informations about turn here. zoom Zooms into the image by a factor equal or superior to 1 towards the focus point while preserving the image size. Syntax: { zoom: number } <NuxtImg provider="twicpics" src="/cherry-3.jpg" :modifiers="{zoom:1.5}" <!-- zooms into image by a factor 1.5 --> /> <NuxtImg provider="twicpics" src="/cherry-3.jpg" :modifiers="{zoom:3}" <!-- zooms into image by a factor 3 --> /> <NuxtImg provider="twicpics" src="/cherry-3.jpg" :modifiers="{focus:'auto', zoom:3}" <!-- zooms into image by a factor 3 in direction of the focus--> /> <NuxtImg provider="twicpics" src="/cherry-3.jpg" :modifiers="{focus:'200x200', zoom:3}" <!-- zooms into image by a factor 3 in direction of the focus--> /> More informations about zoom here. Combination of parameters You can combine several transformations of the TwicPics API. Be aware that the order of the parameters can be significant. Example: This will return a variant of image for which we have, in order: cropped the image from the center to 16:9 aspect ratio then placed the focus on the center of interest of the cropped image then rotate the image 90° to the left The result is a 9:16 (not 16:9) image with a possibly false area of interest. <NuxtImg provider="twicpics" src="/football.jpg" :modifiers="{cover:'16:9', focus:'auto', turn:'left'}" /> This will return a variant of your image for which we have, in order: placed the focus on the center of interest of the original image then cropped the image to 16:9 from the center of interest then rotated the image 90° to the left The result is a cropped image with the area of interest retained and displayed in 16:9 format. <NuxtImg provider="twicpics" src="/football.jpg" fit="fill" :modifiers="{focus:'auto', turn:'left', cover:'16:9'}" /> Dealing with image ratio Let's say you want to display an image in 4:3 aspect ratio with a width of 300px. <NuxtImg provider="twicpics" src="/cat_1x1.jpg" width=300 fit="fill" :modifiers="{cover:'4:3'}" /> Or, with focus='auto' <NuxtImg provider="twicpics" src="/cat_1x1.jpg" width=300 fit="fill" :modifiers="{focus:'auto', cover:'4:3'}" /> Go further with TwicPics TwicPics offers a collection of web components that will allow you to exploit all its power : Pixel Perfect Layout Driven Ideal Compression Lazy Loading LQIP CLS Optimization A specific integration to Nuxt is available here. Strapi Nuxt Image with Strapi integration. Unsplash Nuxt Image has first class integration with Unsplash.
Twicpics - Nuxt Image Providers
https://image.nuxt.com/advanced/static-images
Advanced Static Images Optimizing images for static websites. If you are building a static site using nuxt generate, Nuxt Image will optimize and save your images locally when your site is generated - and deploy them alongside your generated pages. If you disabled server-side rendering (ssr: false in the nuxt.config), Nuxt Image won't be able to optimize your images during the static generation process. In that case, you can tell Nuxt to pre-render images by using the nitro.prerender.routes option: export default defineNuxtConfig({ ssr: false, nitro: { prerender: { routes: [ '/_ipx/w_120/market.jpg', '/_ipx/w_140/market.jpg', // etc. ] } } }) Custom Provider If a CDN provider is not supported, you can define it yourself.
Static Images - Nuxt Image
https://image.nuxt.com/advanced/custom-provider
Advanced Custom Provider If a CDN provider is not supported, you can define it yourself. Provider Entry The runtime will receive a source, image modifiers and its provider options. It is responsible for generating a url for optimized images, and needs to be isomorphic because it may be called on either server or client. providers/my-provider.ts import { joinURL } from 'ufo' import type { ProviderGetImage } from '@nuxt/image' import { createOperationsGenerator } from '#image' const operationsGenerator = createOperationsGenerator() export const getImage: ProviderGetImage = ( src, { modifiers = {}, baseURL } = {} ) => { if (!baseURL) { // also support runtime config baseURL = useRuntimeConfig().public.siteUrl } const operations = operationsGenerator(modifiers) return { url: joinURL(baseURL, src + (operations ? '?' + operations : '')), } } Parameters src: Source path of the image. modifiers: List of image modifiers that are defined in the image component or as a preset. ctx: (ImageCTX) Image module runtime context options: (CreateImageOptions) Image module global runtime options $img: The $img helper Note: Values in ctx might change. Use it with caution. Return url: Absolute or relative url of optimized image. Use your provider Register provider After you create your own provider, you should register it in the nuxt.config. In order to do that create a property inside image.provider. nuxt.config.ts export default defineNuxtConfig({ // ... image: { providers: { myProvider: { name: 'myProvider', // optional value to overrider provider name provider: '~/providers/my-provider.ts', // Path to custom provider options: { // ... provider options baseURL: "https://site.com" } } } } }) There are plenty of useful utilities that can be used to write providers by importing from #image. See src/runtime/providers for more info. Usage Set attribute provider as your custom provider name. pages/index.vue <NuxtImg provider="myProvider" src="/image.png" > <!-- <img src="https://site.com/image.png" /> --> Vercel Optimize images at Vercel's Edge Network. Static Images Optimizing images for static websites.
Custom Provider - Nuxt Image
https://image.nuxt.com/providers/vercel
Providers Vercel Source Optimize images at Vercel's Edge Network. When deploying your nuxt applications to Vercel platform, image module can use Vercel's Edge Network to optimize images on demand. This provider will be enabled by default in vercel deployments. Domains To use external URLs (images not in public/ directory), hostnames should be whitelisted. Example: nuxt.config export default { image: { domains: [ 'avatars0.githubusercontent.com' ] } } Sizes Specify any custom width property you use in <NuxtImg>, <NuxtPicture> and $img. If a width is not defined, image will fallback to the next bigger width. Example: nuxt.config export default { image: { screens: { icon: 40, avatar: 24 } } } Uploadcare Power up file uploading, processing and delivery for your app in one sitting. Custom Provider If a CDN provider is not supported, you can define it yourself.
Vercel - Nuxt Image Providers
https://image.nuxt.com/providers/uploadcare
Providers Uploadcare Source Power up file uploading, processing and delivery for your app in one sitting. Integration between Uploadcare and the Nuxt Image module. Usage To use images from uploadcare, specify the provider as uploadcare and set the image src to the UUID provided on the dashboard. page.vue <NuxtImg provider="uploadcare" src="c160afba-8b42-45a9-a46a-d393248b0072" alt="My image from uploadcare" /> Modifiers To see all possible modifiers and their options, check out the image transformations documentation or the URL API Reference. Types are provided for the following modifiers: src/types/module.ts // Image Compression format: 'jpeg' | 'png' | 'webp' | 'auto' quality: 'smart' | 'smart_retina' | 'normal' | 'better' | 'best' | 'lighter' | 'lightest' progressive: 'yes' | 'no' strip_meta: 'all' | 'none' | 'sensitive' // Image Geometry preview: `${number}x${number}` // Height x Width resize: `${number}x${number}` | `${number}x`| `x${number}` smart_resize: `${number}x${number}` crop: string | string[] scale_crop: string | string[] border_radius: string | string[] setfill: string // 3, 6 or 8 digit hex color zoom_objects: string // 1 to 100 Please feel free to open a PR to improve support for additional operations. Configuration By default, all file URLs use the ucarecdn.com domain. By setting a custom CDN CNAME, file URLs can use cdn.mycompany.com instead. See the Uploadcare documentation for how to enable a custom domain in your project. To tell Nuxt Image about the custom CDN name, use the following configuration: nuxt.config.ts export default defineNuxtConfig({ image: { uploadcare: { cdnURL: 'cdn.mycompany.com', } } }) Unsplash Nuxt Image has first class integration with Unsplash. Vercel Optimize images at Vercel's Edge Network.
Uploadcare - Nuxt Image Providers
https://image.nuxt.com/providers/unsplash
Providers Unsplash Source Nuxt Image has first class integration with Unsplash. Integration between Unsplash and the image module. See Unsplash License for what usage is permitted. Dynamically resizable images Every image returned by the Unsplash API is a dynamic image URL, which means that it can be manipulated to create new transformations of the image by simply adjusting the query parameters of the image URL. This enables resizing, cropping, compression, and changing the format of the image in realtime client-side, without any API calls. Under the hood, Unsplash uses Imgix, a powerful image manipulation service to provide dynamic image URLs. Supported parameters Unsplash officially support the parameters: w, h: for adjusting the width and height of a photo crop: for applying cropping to the photo fm: for converting image format auto=format: for automatically choosing the optimal image format depending on user browser q: for changing the compression quality when using lossy file formats fit: for changing the fit of the image within the specified dimensions dpr: for adjusting the device pixel ratio of the image The other parameters offered by Imgix can be used, but we don’t officially support them and may remove support for them at any time in the future. 💫 Tip The API returns image URLs containing an ixid parameter. All resizing and manipulations of image URLs must keep this parameter as it allows for your application to report photo views and be compliant with the API Guidelines. Twicpics Nuxt Image internally use Twicpics as static provider. Uploadcare Power up file uploading, processing and delivery for your app in one sitting.
Unsplash - Nuxt Image Providers
https://image.nuxt.com/providers/sirv
Providers Sirv Source Nuxt Image integration with Sirv media management, transformation and delivery platform. Integration between Sirv and Nuxt image. To use Sirv provider, you need to set up your Sirv URL as the baseURL in the Nuxt Image module configuration, like this: nuxt.config.ts export default defineNuxtConfig({ image: { sirv: { baseURL: 'https://youralias.sirv.com/' } } }) Get your alias from your Sirv account details page or set up a custom domain (instructions). Sirv fit parameters By default, Sirv will scale the image, preserving its aspect ratio, to fit within the smallest dimension. Here's the map of standard values for the fit property and how they're going to be interpreted by Sirv: fill: ignore inside: fill outside: fill noUpscaling: noup, this is the default option for Sirv image provider, so you don't need to specify it explicitly. format If no format is specified, Sirv will deliver your images in the optimal format by default. Alternatively, you can specify a custom format for the image like this: <NuxtImg provider="sirv" src="/example-image.jpg" width="300" format="webp" /> Sirv modifiers To use Sirv-specific transformations, add them in the modifier prop. profile Use Sirv profiles to combine multiple transformation options into a single parameter. For example, you can combine canvas, crop and watermark parameters into a single profile and use it like this: <NuxtImg provider="sirv" src="/example-image.jpg" width="300" :modifiers="{profile: 'my-profile'} /> canvas Use the canvas modifier to add a canvas around your image. You can also set its width, height, color, and position. sharpen Sharpen the image using the sharpen modifier. <NuxtImg provider="sirv" src="/example-image.jpg" width="300" :modifiers="{sharpen: 50}" /> frame Add a frame/border to your images using the frame modifier. You can also set its width and color. <NuxtImg provider="sirv" src="/example-image.jpg" width="300" :modifiers="{ frameStyle: 'solid', frameColor: '00000', frameWidth: '2', frameRimColor: '97A6B1', frameRimWidth: '2' }" /> rotate Use the rotate modifier to rotate your image. You can specify the number of degrees to rotate the image by. <NuxtImg provider="sirv" src="/example-image.jpg" :modifiers="{rotate: 90}" /> Color and light options Sirv has various color manipulation options like grayscale, colorize,colortone,colorLevels, as well as light manipulation options like lightness, hue, saturation, highlights, shadows, brightness, exposure, contrast. Here's how to convert an image to grayscale: <NuxtImg provider="sirv" src="/example-image.jpg" width="300" :modifiers="{grayscale: true}" /> Watermarks and text overlays Using Sirv's Nuxt Image integration, you can overlay images or text over other images for watermarking or creating a dynamic banner using custom text! watermark Add an image overlay over your existing image using the watermark modifier. Used mostly for watermarking, but can be useful for creating banners, OG images, and personalization. Here's an example of a single watermark: <NuxtImg provider="sirv" src="example-image.jpg" width="300" :modifiers="{ watermark: '/watermark-v1.png', watermarkPosition: 'center', watermarkWidth: '30%', }" /> Find out more about Sirv watermarks here. Overlay Text You can add text overlays to your images and have full freedom over their positioning and looks. <NuxtImg provider="sirv" src="example-image.jpg" width="300" :modifiers="{ text: 'Hello there', textAlign: 'center', textPositionGravity: 'south', textBackgroundColor: '#ffff', textSize: 60, textFontFamily: 'Arial', textColor: 'white', }" /> More examples of text overlays can be found here. List of supported transformations Sirv's Nuxt Image integration uses intuitive names for each transformation. If you use a property that does not match any of the following supported options, it will be added in the URL as it is. Supported Parameter Name Translates to Parameter Description width w Width of image. height h Height of image. s s Resize the image by its biggest side quality q JPEG image quality (percentage). fit scale.option Image scaling options. profile profile Apply a Sirv profile format format Image format served (defaults to optimal). webpFallback webp-fallback Image format for browsers without WebP support. subsampling subsampling Chroma subsampling to reduce JPEG file size. gifCompression gif.lossy Apply lossy compression, to reduce GIF file size. crop crop.type Automatically crop to edge of image contents; point of interest; or face. cropAr crop.aspectratio Aspect ratio of the crop cw cw Crop the image to a specific width. ch ch Crop the image to a specific height. cx cx Position to start image crop (from top). cy cy Position to start image crop (from left). cropPaddingX crop.pad.x Add padding to left/right of crop area cropPaddingY crop.pad.y Add padding to top/bottom of crop area. canvasHeight canvas.height Create a canvas around the image (height). canvasWidth canvas.width Create a canvas around the image (width). canvasAr canvas.aspectratio Aspect ratio of the canvas from 1-99 e.g. 16:9 canvasPosition canvas.position Position of the canvas behind the image. canvasBorderWidth canvas.border.width Adds additional width left and right of the canvas. canvasBorderHeight canvas.border.height Adds additional height above and below the canvas. canvasBorderColor canvas.border.color Color of the canvas border e.g. E0AA80 or red. canvasBorderOpacity canvas.border.opacity Opacity of the canvas border. watermark watermark Filepath of the image to be overlayed. watermarkPosition watermark.position Position of the watermark on the image. watermarkPositionGravity watermark.position.gravity sets the starting point for shifting the x & y values. watermarkPositionX watermark.position.x Position of the watermark (from left). watermarkPositionY watermark.position.y Position of the watermark (from top). watermarkWidth watermark.scale.width Width of watermark. watermarkHeight watermark.scale.height Height of watermark. text text Display text on your image. textBase64 text.text64 Alternative to text parameter, with Base64 encoding textSize text.size Width of text area in relation to image. textAlign text.align Align the multiline text. textPosition text.position Location of the text on the image. textPositionX text.position.x Location of the text (from left). textPositionY text.position.y Location of the text (from top). textPositionGravity text.position.gravity Master location of the text on the image. textFontSize text.font.size Fix the size of the text in px. textFontStyle text.font.style Style of the text. textFontFamily text.font.family Choose a font e.g. "Open Sans". textFontWeight text.font.weight Choose font weight (light, normal, semi-bold, bold, extra-bold). textColor text.color Text color e.g. E0AA80 or E0AA8020. textOpacity text.opacity Text opacity. textOutlineWidth text.outline.width Add an outline around the text. textoutlineColor text.outline.color Color of the text outline. textOutlineOpacity text.outline.opacity Opacity of the text outline. textOutlineBlur text.outline.blur Blur the edge of the text outline. textBackgroundColor text.background.color Background color e.g. E0AA80 or E0AA8020. textBackgroundOpacity text.background.opacity Background opacity. sharpen sharpen Sharpen the image. blur blur Blur the image. grayscale grayscale Make the image black & white. colorize colorize Overlay a color on the image. colorizeColor colorize.color The color of the colorize option. colorizeOpacity colorize.opacity Opacity of the color overlay. colortone colortone Change the color tone of the image. colortoneColor colortone.color Apply a color tone to an image. colortoneLevel colortone.level Set the level of blending with the original image. colortoneMode colortone.mode Apply the color tone to the entire image or shadows/highlights only. vignette vigette.value Adjust the depth of the vignette. vignetteColor vigette.color Add a vignette (dark edges) around the image. lightness lightness Change the lightness of the image. colorlevelBlack colorlevel.black Adjust black level of image. colorlevelWhite colorlevel.white Adjust white level of image. histogram histogram Display a histogram of RGB levels. hue hue Change the hue of the image. saturation saturation Change the saturation of the image. highlights highlights Change the highlights of the image. shadows shadows Change the shadows of the image. brightness brightness Change the brightness of the image. exposure exposure Change the exposure of the image. contrast contrast Change the contrast of the image. rotate rotate Number of degrees to rotate the image. flip flip Flip image vertically (mirror). flop flop Flip image horizontally (mirror). opacity opacity Opacity of PNG images. frameStyle frame.style Add a frame around the image. frameColor frame.color Frame color e.g. E0AA80 or E0AA8020. frameWidth frame.width Frame width. frameRimColor frame.rim.color Frame rim color e.g. E0AA80 or E0AA8020. frameRimWidth frame.rim.width Frame rim width. pdfPage page Page number of PDF when converted to image. Learn more about Sirv's Image transformations from the official documentation. Sanity Nuxt Image has first class integration with Sanity. Storyblok Nuxt Image internally use Storyblok as static provider.
Sirv - Nuxt Image Providers
https://image.nuxt.com/providers/storyblok
Providers Storyblok Source Nuxt Image internally use Storyblok as static provider. Integration between Storyblok and the image module. To use this provider you just need to specify the base url of your service in Storyblok. nuxt.config.ts export default defineNuxtConfig({ image: { storyblok: { baseURL: 'https://a.storyblok.com' } } }) Storyblok modifiers I am following all modifiers present on Storyblok image service Resizing Check Storyblok documentation if you want to know more. the logic is: If you do not define either width or height, the image will not be resized. If you define only width or only height the image will be proportionately resized based on the one you defined. Example: <div>Original</div> <NuxtImg provider="storyblok" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> <div>Resized static</div> <NuxtImg width="500" height="500" provider="storyblok" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> <div>Proportional to Width</div> <NuxtImg width="500" provider="storyblok" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> <div>Proportional to Height</div> <NuxtImg height="500" provider="storyblok" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> Fit in with background or not Check Storyblok documentation if you want to know more. If you want to use it just add a props fit="in". Take care that storyblok only support fit-in. You can also use the fill filters to fill your fit-in with a specific background. If you not defining value it will be transparent. Example: <div>Fit in with background CCCCCC</div> <NuxtImg width="200" height="200" fit="in" :modifiers="{ filters: { fill: 'CCCCCC' } }" provider="storyblok" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> Format Check Storyblok documentation if you want to know more. You can modify your image format. Supported format are webp, jpeg and png. Example: <h3>Format</h3> <NuxtImg width="200" format="webp" provider="storyblok" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> Quality Check Storyblok documentation if you want to know more. You can update your image quality by defining the quality filters. Example: <div class="flex"> <div>Resized and 10% Quality</div> <NuxtImg provider="storyblok" width="200" quality="10" src="https://a.storyblok.com/f/39898/3310x2192/e4ec08624e/demo-image.jpeg" /> </div> Facial detection Check Storyblok documentation if you want to know more. To have a smart crop just define a smart property inside modifier. Example: <h3>Facial detection</h3> <div>Resized without Smart Crop</div> <NuxtImg width="600" height="130" provider="storyblok" src="https://a.storyblok.com/f/39898/2250x1500/c15735a73c/demo-image-human.jpeg" /> <div>Resized with Smart Crop</div> <NuxtImg width="600" height="130" :modifiers="{ smart: true }" provider="storyblok" src="https://a.storyblok.com/f/39898/2250x1500/c15735a73c/demo-image-human.jpeg" /> Custom focal point Check Storyblok documentation if you want to know more. Storyblok offer you the focalize on a specific part of your image. Just use focal filters. Example: <div>Focus on the bottom of the image</div> <NuxtImg width="600" height="130" :modifiers="{ filters: { focal: '450x500:550x600' } }" provider="storyblok" src="https://a.storyblok.com/f/39898/1000x600/d962430746/demo-image-human.jpeg" /> <div>Focus on the top of the image</div> <NuxtImg width="600" height="130" :modifiers="{ filters: { focal: '450x0:550x100' } }" provider="storyblok" src="https://a.storyblok.com/f/39898/1000x600/d962430746/demo-image-human.jpeg" /> Sirv Nuxt Image integration with Sirv media management, transformation and delivery platform. Strapi Nuxt Image with Strapi integration.
Storyblok - Nuxt Image Providers
https://image.nuxt.com/providers/strapi
Providers Strapi Source Nuxt Image with Strapi integration. Integration between Strapi and the image module. No specific configuration is required. You just need to specify strapi in your configuration to make it the default: nuxt.config.ts export default defineNuxtConfig({ image: { strapi: {} } }) Override default options: nuxt.config.ts export default defineNuxtConfig({ image: { strapi: { baseURL: 'http://localhost:1337/uploads/' } } }) Modifiers The breakpoint modifier is used to specify the size of the image. By default, when the image is uploaded and Enable responsive friendly upload Strapi setting is enabled in the settings panel the plugin will generate the following responsive image sizes: Name Largest Dimension small 500px medium 750px large 1000px You can override the default breakpoints. See the Upload configuration in the Strapi documentation. If you don't set breakpoint modifier, the original image size will be used: <NuxtImg provider="strapi" src="..." /> Define breakpoint modifier: <NuxtImg provider="strapi" src="..." :modifiers="{ breakpoint: 'small' }" /> Only one breakpoint can be modified per image. Storyblok Nuxt Image internally use Storyblok as static provider. Twicpics Nuxt Image internally use Twicpics as static provider.
Strapi - Nuxt Image Providers
https://image.nuxt.com/providers/prepr
Providers Prepr Source Nuxt Image integration with Prepr CMS. Integration between Prepr and Nuxt Image. To use this provider you just need to specify the projectName of your project in Prepr. nuxt.config.ts export default defineNuxtConfig({ image: { prepr: { // E.g.: https://YourProjectName.prepr.io/ projectName: 'YourProjectName', } } }) Modifiers The Prepr provider supports a number of additional modifiers. For a full list, check out the Prepr documentation. All current transformations currently mentioned in Prepr docs are supported. For the time being you might find the following links useful: Assets Resizing via REST API Understanding your marketing and design team workflows prepr.io does not provide a way to restrict what domains can request assets to your project's CDN, nor limit the maximum size in pixels or bytes of images that are served from the CDN. Convenience key modifiers The following more readable modifiers are supported, in addition to Prepr's native modifiers: crop is equivalent to c format is equivalent to format height is equivalent to h quality is equivalent to q width is equivalent to w fit In addition to the values specified in the Prepr docs, which are respected, the following options from the default fit behavior are supported: cover - this will behave like the Prepr modifier crop, when passed without a value (defaults to centre) For the time being, other fit options are not supported by this provider. Netlify Optimize images with Netlify's dynamic image transformation service. Prismic Nuxt Image has first class integration with Prismic.
Prepr - Nuxt Image Providers
https://image.nuxt.com/providers/sanity
Providers Sanity Source Nuxt Image has first class integration with Sanity. Integration between Sanity and Nuxt Image. To use this provider you just need to specify the projectId of your project in Sanity. nuxt.config.ts export default defineNuxtConfig({ image: { sanity: { projectId: 'yourprojectid', // Defaults to 'production' // dataset: 'development' } } }) Modifiers The Sanity provider supports a number of additional modifiers. For a full list, check out the Sanity documentation. All of the modifiers mentioned in the Sanity docs are supported, with the following notes. Extra convenience modifiers The following more readable modifiers are also supported: background - equivalent to bg download - equivalent to dl sharpen - equivalent to sharp orientation - equivalent to or minHeight or min-height - equivalent to min-h maxHeight or max-height - equivalent to max-h minWidth or min-width - equivalent to min-w maxWidth or max-width - equivalent to max-w saturation - equivalent to sat fit In addition to the values specified in the Sanity docs, which are respected, the following options from the default fit behavior are supported: cover - this will behave like the Sanity modifier crop contain - this will behave like the Sanity modifier fill, and defaults to filling with a white background. (You can specify your own background color with the background modifier.) inside - this will behave like the Sanity modifier min outside - this will behave like the Sanity modifier max fill - this will behave like the Sanity modifier scale For compatibility with other providers, fit: fill is equivalent to the Sanity parameter ?fit=scale. If you need the Sanity ?fit=fill behavior, use fit: contain instead. format You can specify any of the formats suppored by Sanity. If this is omitted, the Sanity provider will default to auto=format. crop and hotspot You can pass your Sanity crop and hotspot image data as modifiers and Nuxt Image will correctly generate the rect, fp-x and fp-y parameters for you. Prismic Nuxt Image has first class integration with Prismic. Sirv Nuxt Image integration with Sirv media management, transformation and delivery platform.
Sanity - Nuxt Image Providers
https://image.nuxt.com/providers/prismic
Providers Prismic Source Nuxt Image has first class integration with Prismic. Integration between Prismic and the image module. No specific configuration is required for Prismic support. You just need to specify provider: 'prismic' in your configuration to make it the default: nuxt.config.ts export default defineNuxtConfig({ image: { prismic: {} } }) You can also pass it directly to your component when you need it, for example: *.vue <NuxtImg provider="prismic" src="..." /> Prismic allows content writer to manipulate images through its UI (cropping, rezising, etc.). To preserve that behavior this provider does not strip query parameters coming from Prismic. Instead it only overrides them when needed, keeping developers in control. Prepr Nuxt Image integration with Prepr CMS. Sanity Nuxt Image has first class integration with Sanity.
Prismic - Nuxt Image Providers
https://image.nuxt.com/providers/netlify
Providers Netlify Source Optimize images with Netlify's dynamic image transformation service. Netlify offers dynamic image transformation for all JPEG, PNG, and GIF files you have set to be tracked with Netlify Large Media. Before setting provider: 'netlify', make sure you have followed the steps to enable Netlify Large Media. Modifiers In addition to height and width, the Netlify provider supports the following modifiers: fit Default: contain Valid options: contain (equivalent to nf_resize=fit) and fill (equivalent to nf_resize=smartcrop) IPX IPX is the built-in and self hosted image optimizer for Nuxt Image. Prepr Nuxt Image integration with Prepr CMS.
Netlify - Nuxt Image Providers
https://image.nuxt.com/providers/imgix
Providers Imgix Source Nuxt Image has first class integration with Imgix. Integration between Imgix and the image module. To use this provider you just need to specify the base url of your service in Imgix. nuxt.config.ts export default defineNuxtConfig({ image: { imgix: { baseURL: 'https://assets.imgix.net' } } }) imgix fit values Beside the standard values for fit property of Nuxt image and Nuxt picture, imgix offers the following for extra resizing experience: clamp - Resizes the image to fit within the width and height dimensions without cropping or distorting the image, and the remaining space is filled with extended pixels from the edge of the image. The resulting image will match the constraining dimensions. The pixel extension is called an affine clamp, hence the value name, "clamp". clip - The default fit setting for imgix images. Resizes the image to fit within the width and height boundaries without cropping or distorting the image. The resulting image will match one of the constraining dimensions, while the other dimension is altered to maintain the same aspect ratio of the input image. facearea - Finds the area containing all faces, or a specific face in an image, and scales it to specified width and height dimensions. Can be used in conjunction with faceindex to identify a specific face, as well as facepad to include additional padded area around the face to zoom out from the immediate area around the faces. fillMax - Resizes the image to fit within the requested width and height dimensions while preserving the original aspect ratio and without discarding any original image data. If the requested width or height exceeds that of the original, the original image remains the same size. The excess space is filled with a solid color or blurred version of the image. The resulting image exactly matches the requested dimensions. imgix modifiers Beside the standard modifiers, you can also pass all imgix-specific render API parameters to the modifiers prop. For a full list of these modifiers and their uses, check out imgix's image Rendering API documentation. imgix best practices Some common best practices when using imgix, would be to include our auto parameter, which will automatically apply the best format for an image and compress the image as well. Combine this with some top of intelligent cropping and resizing and you will have a great image! <NuxtImg provider="imgix" src="/blog/woman-hat.jpg" width="300" height="500" fit="cover" :modifiers="{ auto: 'format,compress', crop: 'faces' }" /> This will return a 300 x 500 image, which has been compressed, will display next-gen formats for a browser, and has been cropped intelligently to the face of the woman in the hat. Additional Documentation You can find additional documentation and a step-by-step tutorial in an imgix blog article titled Using the New Nuxt Component with imgix. ImageKit Nuxt Image has first class integration with ImageKit. IPX IPX is the built-in and self hosted image optimizer for Nuxt Image.
Imgix - Nuxt Image Providers
https://image.nuxt.com/providers/imagekit
Providers ImageKit Source Nuxt Image has first class integration with ImageKit. Integration between ImageKit and the image module. To use the ImageKit provider, you need to set your ImageKit account URL-endpoint as the base url like below. nuxt.config.ts export default defineNuxtConfig({ image: { imagekit: { baseURL: 'https://ik.imagekit.io/your_imagekit_id' } } }) You can get URL-endpoint from your ImageKit dashboard - https://imagekit.io/dashboard#url-endpoints. ImageKit fit Parameters In addition to the standard fit properties of Nuxt Image and Nuxt Picture, ImageKit offers more cropping and resizing options to the users: extract - The output image has its height, width as requested, and the aspect ratio is preserved. Unlike the cover parameter, we extract out a region of the requested dimension from the original image. pad_extract - This parameter is similar to extract. This comes in handy in scenarios where we want to extract an image of a larger dimension from a smaller image. So, the pad_extract mode adds solid colored padding around the image to match the exact size requested. Read ImageKit crop and crop mode documentation for more details and examples of how it works. ImageKit Modifiers On top of the standard Nuxt Image modifiers, a user can also leverage ImageKit-specific transformation parameters provided in the modifier prop. focus This parameter can be used along with resizing and cropping to focus on the desired part of the image. You can use focus parameter values like left, right, top, bottom, center, top, left, bottom, right, top_left, top_right, bottom_left and bottom_right. Custom coordinates can also be used to focus using parameter value custom. Learn more from example. Moreover, ImageKit also provides smart cropping that can automatically detect the most important part of the image using auto. And, face can be used to find a face (or multiple faces) in an image and focus on that. Check out ImageKit's documentation on focus to learn more. blur This can be used to blur an image. Use modifier blur to specify the Gaussian Blur radius that is to be applied to the image. Possible values include integers between 1 to 100. <NuxtImg provider="imagekit" src="/default-image.jpg" :modifiers="{blur: 10}" /> effectGray Turn your image to a grayscale version using the effectGray modifier. <NuxtImg provider="imagekit" src="/default-image.jpg" height="300" :modifiers="{effectGray: true}" /> named Use named transformations as an alias for an entire transformation string. For example, we can create a named transformation - media_library_thumbnail for a transformation string - tr:w-100,h-100,c-at_max,fo-auto. border Add a border to your images using the border modifier. You can also set its width and color. <NuxtImg provider="imagekit" src="/default-image.jpg" width="300" :modifiers="{border: '20_FF0000'}" /> rotate Use the rotate modifier to rotate your image. Possible values are - 0, 90, 180, 270, 360, and auto. <NuxtImg provider="imagekit" src="/default-image.jpg" :modifiers="{rotate: 90}" /> radius Give rounded corners to your image using radius. Possible values are - positive integers and max. <NuxtImg provider="imagekit" src="/default-image.jpg" :modifiers="{radius: 20}" /> bg Specify background color and its opacity for your image using the bg modifier. <NuxtImg provider="imagekit" src="/default-image.jpg" height="1200" width="1200" fit="pad_extract" :modifiers="{bg: '272B38'}" /> Read more about ImageKit crop, resize, and other common transformations here. Overlay Transformation Modifiers Using ImageKit's Nuxt Image integration, you can overlay images or text over other images for watermarking or creating a dynamic banner using custom text! overlayImage Overlay an image on top of another image (base image) using the overlayImage modifier. You can use this to create dynamic banners, watermarking, etc. <NuxtImg provider="imagekit" src="/default-image.jpg" :modifiers="modifiers" /> <script> export default { data() { return { modifiers: { overlayImage: 'default-image.jpg', overlaywidth: 300, overlayHeight: 200, overlayFocus: 'top_left', overlayImageBorder: '5_FFFFFF', } } } } </script> Overlay Text You can overlay text on an image and apply various transformations to it as per your needs. <NuxtImg provider="imagekit" src="/default-image.jpg" :modifiers="modifiers" /> <script> export default { data() { return { modifiers: { overlayText: 'overlay made easy', overlayRadius: 30, overlayTextBackground: 'FFFFFF80', overlayTextFontSize: '45', overlayTextColor: '000000', overlayTextPadding: '40' } } } } </script> Read more about ImageKit's overlay transformation parameters here. Image Enhancement Modifiers effectContrast Enhance contrast of an image using the effectContrast modifier. <NuxtImg provider="imagekit" src="/default-image.jpg" height="300" :modifiers="{effectContrast: true}" /> effectSharpen Sharpen the input image using the effectSharpen modifier. <NuxtImg provider="imagekit" src="/default-image.jpg" height="300" :modifiers="{effectSharpen: 10}" /> List of supported transforms ImageKit's Nuxt Image integration provides an easy-to-remember name for each transformation parameter. It makes your code more readable. If you use a property that does not match any of the following supported options, it will be added in the URL as it is. Supported Parameter Name Translates to Parameter bg bg aspectRatio ar x x y y xc xc yc yc oix oix oiy oiy oixc oixc oiyc oiyc crop c cropMode cm focus fo radius r border b rotate rt blur bl named n overlayX ox overlayY oy overlayFocus ofo overlayHeight oh overlayWidth ow overlayImage oi overlayImageTrim oit overlayImageAspectRatio oiar overlayImageBackground oibg overlayImageBorder oib overlayImageDPR oidpr overlayImageQuality oiq overlayImageCropping oic overlayImageCropMode oicm overlayText ot overlayTextFontSize ots overlayTextFontFamily otf overlayTextColor otc overlayTextTransparency oa overlayTextTypography ott overlayBackground obg overlayTextEncoded ote overlayTextWidth otw overlayTextBackground otbg overlayTextPadding otp overlayTextInnerAlignment otia overlayRadius or progressive pr lossless lo trim t metadata md colorProfile cp defaultImage di dpr dpr effectSharpen e-sharpen effectUSM e-usm effectContrast e-contrast effectGray e-grayscale original orig Learn more about ImageKit's Image transformations from the official documentation. ImageEngine Nuxt Image has first class integration with ImageEngine. Imgix Nuxt Image has first class integration with Imgix.
ImageKit - Nuxt Image Providers
https://image.nuxt.com/providers/ipx
Providers IPX Source IPX is the built-in and self hosted image optimizer for Nuxt Image. Nuxt Image comes with a preconfigured instance of unjs/ipx. An open source, self-hosted image optimizer based on lovell/sharp. Additional Modifiers You can use additional modifiers supported by IPX. Example: <NuxtImg src="/image.png" :modifiers="{ grayscale: true, tint: '#00DC82' }" /> Imgix Nuxt Image has first class integration with Imgix. Netlify Optimize images with Netlify's dynamic image transformation service.
IPX - Nuxt Image Providers
https://image.nuxt.com/providers/imageengine
Providers ImageEngine Source Nuxt Image has first class integration with ImageEngine. Integration between ImageEngine and the image module. At a minimum, you must configure the imageengine provider with the baseURL set to your ImageEngine Delivery Address: nuxt.config.ts export default defineNuxtConfig({ image: { imageengine: { baseURL: 'https://xxxxx.imgeng.in' } } }) ImageEngine fit values The standard values for fit property map onto ImageEngine Directives as follows: cover: m_cropbox contain: m_letterbox fill: m_stretch inside: m_box, this is the default fit method for the ImageEngine provider. outside: This fit method is not supported and functions the same as inside. ImageEngine modifiers In addition to the standard modifiers, you can also use all ImageEngine Directives by adding them to the modifiers property with the following attribute names: format: f directive fit: m directive passThrough: pass directive sharpen: s directive rotate: r directive screenPercent: pc directive crop: cr directive inline: in directive metadata: meta directive Note that the standard quality attribute is converted to the ImageEngine cmpr compression directive. quality is the opposite of compression, so 80% quality equals 20% compression. Since ImageEngine automatically adapts image quality the visitor's device, browser and network quality, it is recommended that you do not explicitly set the quality. If you want to completely disable all optimizations to an image, you should use :modifiers="{ passThrough: 'true' }", which will serve the unaltered image. Example 1: Cropping an image to a width and height of 100x80, starting 10 pixels from the top and 20 pixels from the left: <NuxtImg provider="imageengine" src="/some-image.jpg" width="100" height="80" :modifiers="{ cr: '100,80,10,20' }" /> Example 2: Instruct ImageEngine to keep the image's EXIF metadata (which is normally removed to reduce the image byte size): <NuxtImg provider="imageengine" src="/some-image.jpg" width="100" height="80" :modifiers="{ meta: 'true' }" /> ImageEngine best practices Automatic format and quality detection ImageEngine automatically detects the best format and quality for your image based on the characteristics of the specific device that requested it. This feature is very effective and it is not recommended that you disable it, but if you must, you can manually specify the format (ex: format='webp') and quality (quality='80'). ImageEngine settings ImageEngine allows you to set all of the modifiers/directives in the ImageEngine control panel under advanced settings. This is a good place to set default adjustments since you can modify them without having to make changes to your Nuxt codebase. If a directive is set in both Nuxt and the ImageEngine User-Adjustable Settings, the value in Nuxt takes priority. Gumlet Nuxt Image has first class integration with Gumlet. ImageKit Nuxt Image has first class integration with ImageKit.
ImageEngine - Nuxt Image Providers
https://image.nuxt.com/providers/gumlet
Providers Gumlet Source Nuxt Image has first class integration with Gumlet. Integration between Gumlet and the image module. To use this provider you just need to specify the base url of your service in Gumlet. nuxt.config.ts export default defineNuxtConfig({ image: { gumlet: { baseURL: 'https://demo.gumlet.io' } } }) gumlet mode values Gumlet supports all the the standard values for fit property of Nuxt image and Nuxt picture. gumlet modifiers Beside the standard modifiers, you can also pass all gumlet-specific render API parameters to the modifiers prop. For a full list of these modifiers and their uses, check out Gumlet's image Rendering API documentation. gumlet best practices Some common best practices when using Gumlet, would be to include our format=auto parameter, which will automatically apply the best format for an image and compress the image as well. Combine this with some top of intelligent cropping and resizing and you will have a great image! <NuxtImg provider="gumlet" src="/sea.jpeg" width="300" height="500" fit="cover" :modifiers="{ format: 'auto', compress: 'true' }" /> This will return a 300 x 500 image, which has been compressed, will display next-gen formats for a browser, and has been cropped intelligently to the face of the woman in the hat. Glide Nuxt Image has first class integration with Glide. ImageEngine Nuxt Image has first class integration with ImageEngine.
Gumlet - Nuxt Image Providers
https://image.nuxt.com/providers/glide
Providers Glide Source Nuxt Image has first class integration with Glide. Integration between Glide and the image module. To use this provider you just need to specify the base url of your service in glide. nuxt.config.ts export default defineNuxtConfig({ image: { glide: { // baseURL of your laravel application baseURL: 'https://glide.herokuapp.com/1.0/' } } }) Fastly Nuxt Image has first class integration with Fastly. Gumlet Nuxt Image has first class integration with Gumlet.
Glide - Nuxt Image Providers
https://image.nuxt.com/providers/fastly
Providers Fastly Source Nuxt Image has first class integration with Fastly. Integration between Fastly and the image module. To use this provider you just need to specify the base url of your service in Fastly. nuxt.config.ts export default defineNuxtConfig({ image: { fastly: { baseURL: 'https://www.fastly.io' } } }) Edgio Optimize images with Edgio (formerly Layer0)'s optimization service. Glide Nuxt Image has first class integration with Glide.
Fastly - Nuxt Image Providers
https://image.nuxt.com/providers/edgio
Providers Edgio Source Optimize images with Edgio (formerly Layer0)'s optimization service. Edgio provides a simple HTTP service for optimizing images. The image optimizer will only return an optimized image for mobile browsers. Desktop browsers are served the original image. This integration works out of the box without need to configure! See the Documentation for more information. Example: <NuxtImg provider="edgio" src="https://i.imgur.com/LFtQeX2.jpeg" width="200" height="200" quality="80" /> Modifiers Edgio supports the following modifiers: height, width and quality Options baseURL Default: https://opt.moovweb.net Directus Nuxt Image with Directus integration. Fastly Nuxt Image has first class integration with Fastly.
Edgio - Nuxt Image Providers
https://image.nuxt.com/providers/directus
Providers Directus Source Nuxt Image with Directus integration. Integration between Directus and the image module. To use this provider you just need to specify the base URL of your project. nuxt.config.ts export default defineNuxtConfig({ image: { directus: { // This URL needs to include the final `assets/` directory baseURL: 'http://localhost:8055/assets/', } } }) You can easily override default options: nuxt.config.ts export default defineNuxtConfig({ image: { directus: { baseURL: 'http://mydirectus-domain.com/assets/', modifiers: { withoutEnlargement: 'true', transforms: [['blur', 4], ['negate']] } } } }) Modifiers All the default modifiers from Directus documentation are available. <NuxtImg provider="directus" src="ad514db1-eb90-4523-8183-46781437e7ee" height="512" fit="inside" quality="20" :modifiers="{ withoutEnlargement: 'true' }" /> Since Directus exposes the full sharp API through the transforms parameter, we can use it inside our modifiers prop: <NuxtImg provider="directus" src="ad514db1-eb90-4523-8183-46781437e7ee" :modifiers="{ height: '512', withoutEnlargement: 'true', transforms: [['blur', 4], ['negate']] }" /> Note that the transforms parameter, as stated in the Directus documentation, is basically a list of lists. This is to facilitate the use of those sharp functions, like normalise, that would need multiple values in input: transforms: [['normalise', 1, 99], ['blur', 4], ['negate']]. Contentful Nuxt Image has first class integration with Contentful. Edgio Optimize images with Edgio (formerly Layer0)'s optimization service.
Directus - Nuxt Image Providers
https://image.nuxt.com/providers/contentful
Providers Contentful Source Nuxt Image has first class integration with Contentful. Integration between Contentful and the image module. To use this provider you just need to specify the base url of your service in Contentful. nuxt.config.ts export default defineNuxtConfig({ image: { contentful: {} } }) Cloudinary Nuxt Image has first class integration with Cloudinary. Directus Nuxt Image with Directus integration.
Contentful - Nuxt Image Providers
https://image.nuxt.com/providers/cloudinary
Providers Cloudinary Source Nuxt Image has first class integration with Cloudinary. Integration between Cloudinary and the image module. To use this provider you just need to specify the base url of your project in cloudinary. nuxt.config.ts export default defineNuxtConfig({ image: { cloudinary: { baseURL: 'https://res.cloudinary.com/<your-cloud-name>/image/upload/' } } }) Remote Images To handle remote image data, you can either use fetch or upload. Consult the cloudinary documentation for the difference between the two. Fetch nuxt.config.ts export default defineNuxtConfig({ image: { cloudinary: { baseURL: 'https://res.cloudinary.com/<your-cloud-name>/image/fetch/' } } }) <NuxtImg provider="cloudinary" src="https://upload.wikimedia.org/wikipedia/commons/a/ae/Olympic_flag.jpg" width="300" height="200" /> Note: You will need to configure your "Allowed fetch domains" to do the above. Upload nuxt.config.ts export default defineNuxtConfig({ image: { cloudinary: { baseURL: 'https://res.cloudinary.com/<your-cloud-name>/image/upload/<mapping-folder>' } } }) <NuxtImg provider="cloudinary" src="/commons/a/ae/Olympic_flag.jpg" width="300" height="200" /> Note: You will need to configure your "Auto upload mapping" to do the above. Cloudinary fit values Beside the standard values for fit property of Nuxt image and Nuxt picture, Cloudinary offers the following for extra resizing experience: minCover - Same like cover but only resizing if the original image is smaller than the given minimum (width and height). minInside - Same as the inside mode but only if the original image is smaller than the given minimum (width and height). coverLimit - Same as the cover mode but only if the original image is larger than the given limit (width and height) thumbnail- Generate a thumbnail using face detection. cropping - Used to extract a given width & height out of the original image. The original proportions are retained. Check out Cloudinary resize mode Documentation for more details. Cloudinary modifiers Beside the standard modifiers, you can also pass the following Cloudinary-specific transformation params to modifiers prop. The Cloudinary provider automatically enables automatic format selection and automatic quality selection for best performance. rotate Accepted values: Any degree number, or auto_right | auto_left | ignore | vflip | hflip To rotate or flip a given asset by certain degrees, or automatically based on orientation. roundCorner Round the specified corners of the desired image. If pass only a number or max (all corners will be applied). The syntax for other use cases is as below: Using 2 values: top_left_bottom_right_radius:top_right_bottom_left_radius(Example: 20:40) Using 3 values: top_left:top_right_bottom_left:bottom_right (Example: 20:30:40) Using 4 values: top_left:top_right:bottom_left:bottom_right (Example: 20:0:40:40) <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" height="169" :modifiers="{ roundCorner: 'max' }" /> gravity Detemine which part of the image to cropped or to place the overlay. Accepted values: auto, subject, face, sink, faceCenter, multipleFaces, multipleFacesCenter, north, northEast, northWest, west, southWest, south, southEast, east, center <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" height="300" fit="fill" :modifiers="{ gravity: 'subject' }" /> effect Apply a filter or an effect on the desired asset. See Effects for images for the full list of syntax and available effects. <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" height="300" fit="fill" :modifiers="{ effect: 'grayscale' }" /> color Color to use when text captions, shadow effect and colorize effect are in use. <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" :modifiers="{ effect: 'colorize:50', color: 'red' }" /> flags One of more flags to alter the default transformation behavior. See Flags for Images for more information. dpr The target device pixel ratio for the asset. auto means automatically matching the DPR settings in user's device. opacity Adjust the opacity of the desired image. Scale: 0 to 100 (%). <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" :modifiers="{ opacity: 50 }" /> overlay Create a layer over the base image. This can be use with x, y, gravity to customize the position of the overlay. <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="100" height="100" fit="thumb" :modifiers="modifiers" /> <script> export default { data() { return { modifiers: { gravity: 'north', overlay: 'text:default_style:Hello+World', } } } } </script> See Overlay Documentation for more information. underlay Create a layer below a partial-transparent image. This can be use with x, y, gravity to customize the position of the overlay. transformation A pre-defined named transformation to apply to the asset. zoom Use together with fit='crop' or fit='thumb' to decide how much of original image/video surronding the face to keep using face detection. index.vue <template> <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="100" height="100" fit="thumb" :modifiers="modifiers" /> </template> <script> export default { data() { return { modifiers: { zoom: 0.75, gravity: "face" } } } } </script> colorSpace Color space to use for the delivery image url. See Color space Documentation for accepted values details. <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" :modifiers="{ colorSpace: 'srgb' }" /> customFunc Call a custom function on Cloudinary side. See Custom Functions for more details. density To define the density number when converting a vector file to image format. aspectRatio To crop or resize the asset to a new aspect ratio, for use with a crop/resize mode that determines how the asset is adjusted to the new dimensions. See Cloudinary Image Transformation API for more details. Cloudimage Nuxt Image has first class integration with Cloudimage. Contentful Nuxt Image has first class integration with Contentful.
Cloudinary - Nuxt Image Providers
https://image.nuxt.com/providers/cloudimage
Providers Cloudimage Source Nuxt Image has first class integration with Cloudimage. Integration between Cloudimage and the image module. To use this provider you need to specify your Cloudimage token and the baseURL of your image storage. nuxt.config.ts export default defineNuxtConfig({ image: { cloudimage: { token: 'your_cloudimage_token', baseURL: 'origin_image_url' // or alias } } }) Options token Type: String (required) Your Cloudimage customer token. Register for a Cloudimage account to get one. Registration takes less than a minute and is totally free. baseURL Type: String (required) Your origin image URL or storage alias that allows to shorten your origin image URLs. nuxt.config.ts export default defineNuxtConfig({ image: { cloudimage: { token: 'demo', baseURL: 'sample.li' } } }) These formats all work as well: nuxt.config.ts export default defineNuxtConfig({ image: { cloudimage: { token: 'demo', baseURL: 'sample.li/images', baseURL: 'https://sample.li/images', baseURL: '_sl_' // alias defined in your Cloudimage storage settings } } }) apiVersion Type: String Default: empty string Allow using a specific version of the API. For tokens created before 20.10.2021, apiVersion needs to be set to v7. Here's an official demo config. demo is an old token hence apiVersion needs to be defined as well. nuxt.config.ts export default defineNuxtConfig({ image: { cloudimage: { token: 'demo', baseURL: 'sample.li', apiVersion: 'v7' } } }) cdnURL Type: String Default: https://{token}.cloudimg.io/{apiVersion} Replaces the dynamically built URL nuxt.config.ts export default defineNuxtConfig({ image: { cloudimage: { cdnURL: 'https://demo.cloudimg.io/v7', } } }) Cloudimage modifiers Beside the standard modifiers, also you can pass Cloudimage-specific Cloudimage-specific transformation params to modifiers prop. Cloudimage fit values Beside the standard values for fit property of Nuxt image and Nuxt picture, Cloudimage offers the following for extra resizing params: crop - Crops the image to specified dimensions (width and height) and keeps proportions. face - Crops the image automatically keeping the most prominent face. fit - Resizes the image to fit into a specified width and height box, adds padding (image or solid colour) to keep proportions. cropfit - Sets crop or fit resize mode depending on the origin and the desired dimensions. bound - Resizes to a given width and height box and keeps proportions. Similar to fit but without adding padding. boundmin - Resizes an image while bounding the smaller dimension to the desired width or height while keeping proportions. Cloudflare Nuxt Image has first class integration with Cloudflare. Cloudinary Nuxt Image has first class integration with Cloudinary.
Cloudimage - Nuxt Image Providers
https://image.nuxt.com/providers/aws-amplify
Providers AWS Amplify Source Nuxt Image has first class integration with AWS Amplify Hosting Integration between AWS Amplify Hosting and the image module. This provider will be enabled by default in AWS Amplify deployments. This is an experimental preset and will be available soon! 🚀 Domains To use external URLs (images not in public/ directory), hostnames should be whitelisted. Example: nuxt.config export default { image: { domains: [ 'avatars0.githubusercontent.com' ] } } Sizes Specify any custom width property you use in <NuxtImg>, <NuxtPicture> and $img. If a width is not defined, image will fallback to the next bigger width. Example: nuxt.config export default { image: { screens: { icon: 40, avatar: 24 } } } Aliyun Nuxt Image has first class integration with Aliyun. Cloudflare Nuxt Image has first class integration with Cloudflare.
AWS Amplify - Nuxt Image Providers
https://image.nuxt.com/providers/cloudflare
Providers Cloudflare Source Nuxt Image has first class integration with Cloudflare. Integration between Cloudflare and the image module. To use this provider you just need to specify the base url (zone) of your service: nuxt.config.ts export default defineNuxtConfig({ image: { cloudflare: { baseURL: 'https://that-test.site' } } }) Example: <NuxtImg provider="cloudflare" src="/burger.jpeg" height="300" :modifiers="{ fit: 'contain' }" /> Options baseURL Default: / Your deployment's domain (zone). Note: /cdn-cgi/image/ will be automatically appended for generating URLs. AWS Amplify Nuxt Image has first class integration with AWS Amplify Hosting Cloudimage Nuxt Image has first class integration with Cloudimage.
Cloudflare - Nuxt Image Providers
https://image.nuxt.com/providers/aliyun
Providers Aliyun Source Nuxt Image has first class integration with Aliyun. Integration between Aliyun CDN and the image module. To use this provider you just need to specify the base url (zone) of your service: nuxt.config.ts export default defineNuxtConfig({ image: { aliyun: { baseURL: "https://that-test.site", }, }, }); Example: <NuxtImg provider="aliyun" src="/burger.jpeg" height="300" :modifiers="{ fit: 'contain' }" /> Options baseURL Default: / Your deployment's domain (zone). modifiers Example: { resize: { fw: 900, fh: 200 }, rotate:180, bright:50 ... } For more modifiers configuration items, see aliyun cdn docs useImage() A Vue composable that returns a helper function to generate optimized image URLs. AWS Amplify Nuxt Image has first class integration with AWS Amplify Hosting
Aliyun - Nuxt Image Providers
https://image.nuxt.com/usage/use-image
Usage useImage() Source A Vue composable that returns a helper function to generate optimized image URLs. Sometimes you might need to use a generated image URL directly with applied transformations instead of the <NuxtImg> and <NuxtPicture> components. This is where useImage() comes in (and the helper function it returns, which you will often see referenced directly as $img or img). Usage const img = useImage() img(src, modifiers, options) Example: Generate image URL for backgroundImage style. const img = useImage() const backgroundStyles = computed(() => { const imgUrl = img('https://github.com/nuxt.png', { width: 100 }) return { backgroundImage: `url('${imgUrl}')` } }) img.getSizes const img = useImage() img.getSizes(src, { sizes, modifiers }) Unstable: getSizes API might change or be removed. Parameters: src: (string) Source to original image id sizes: (string) List of responsive image sizes ({breakpoint}:{size}{unit}) modifiers: (object) Modifiers passed to provider for resizing and optimizing width: resize to the specified width (in pixels) height: resize to specified height (in pixels) quality: Change image quality (0 to 100) format: Change the image format (any other custom provider modifier) options: (object) provider: (string) Provider name other than default (see providers) preset: Use a preset Example: Responsive srcset with Vuetify v-img <script setup lang="ts"> const props = defineProps({ height: { type: [Number, String], default: 500 }, src: { type: String, default: '/img/header-bg.jpg' } }) const img = useImage() const _srcset = computed(() => { return img.getSizes(props.src, { sizes: 'xs:100vw sm:100vw md:100vw lg:100vw xl:100vw', modifiers: { format: 'webp', quality: 70, height: props.height } }) }) </script> <template> <v-img :lazy-src="img(src, { width: 10, quality: 70 })" :src="img(src, { height, quality: 70 })" :srcset="_srcset.srcset" :height="height" :sizes="_srcset.sizes" ></v-img> </template> <NuxtPicture> Discover how to use and configure the Nuxt Picture component. Aliyun Nuxt Image has first class integration with Aliyun.
useImage() - Nuxt Image
https://image.nuxt.com/usage/nuxt-img
Usage <NuxtImg> Source Discover how to use and configure the Nuxt Image component. <NuxtImg> is a drop-in replacement for the native <img> tag. Uses built-in provider to optimize local and remote images Converts src to provider optimized URLs Automatically resizes images based on width and height Generates responsive sizes when providing sizes option Supports native lazy loading as well as other <img> attributes Usage <NuxtImg> outputs a native img tag directly (without any wrapper around it). Use it like you would use the <img> tag: <NuxtImg src="/nuxt-icon.png" /> Will result in: <img src="/nuxt-icon.png" /> With default provider, you should put /nuxt-icon.png inside public/ directory for Nuxt 3 make the above example work. Props src Path to image file src should be in the form of an absolute path for static images in public/ directory. Otherwise path that is expected by provider that starts with / or a URL. <NuxtImg src="/nuxt.png" /> For image optimization when using external urls in src, we need to whitelist them using domains option. width / height Specify width/height of the image. Use desired width/height for static sized images like icons or avatars Use original image width/height for responsive images (when using sizes) sizes Specify responsive sizes. This is a space-separated list of screen size/width pairs. You can see a list of the defined screen sizes here). By default Nuxt generates responsive-first sizing. If you omit a screen size prefix (like sm:) then this size is the 'default' size of the image. Otherwise, Nuxt will pick the smallest size as the default size of the image. This default size is used up until the next specified screen width, and so on. Each specified size pair applies up - so md:400px means that the image will be sized 400px on md screens and up. Example: <NuxtImg src="/logos/nuxt.png" sizes="100vw sm:50vw md:400px" /> densities To generate special versions of images for screens with increased pixel density. Example: <NuxtImg src="/logos/nuxt.png" height="50" densities="x1 x2" /> <!-- <img src="/_ipx/w_50/logos/nuxt.png" srcset="/_ipx/w_100/logos/nuxt.png x2" /> --> placeholder Display a placeholder image before the actual image is fully loaded. The placeholder prop can be either a string, a boolean, a number, or an array. The usage is shown below for each case. <!-- Automatically generate a placeholder based on the original image --> <nuxt-img src="/nuxt.png" placeholder /> <!-- Set a width, height for the automatically generated placeholder --> <nuxt-img src="/nuxt.png" :placeholder="[50, 25]" /> <!-- Set a width, height, quality & blur for the automatically generated placeholder --> <nuxt-img src="/nuxt.png" :placeholder="[50, 25, 75, 5]" /> <!-- Set the width & height of the automatically generated placeholder, image will be a square --> <nuxt-img src="/nuxt.png" :placeholder="15" /> <!-- Provide your own image --> <nuxt-img src="/nuxt.png" placeholder="./placeholder.png" /> You can also leverage useImage() to generate a placeholder image based on the original image, can be useful if the source is an SVG or you want better control on the modifiers: <script setup> const img = useImage() </script> <template> <NuxtImg :placeholder="img(`/nuxt.svg`, { h: 10, f: 'png', blur: 2, q: 50 })" src="/nuxt.svg`" /> </template> provider Use other provider instead of default provider option specified in nuxt.config Example: index.vue nuxt.config.ts <template> <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" height="169" /> </template> preset Presets are predefined sets of image modifiers that can be used create unified form of images in your projects. We can define presets using presets options in nuxt.config index.vue nuxt.config.ts <template> <NuxtImg preset="cover" src="/nuxt-icon.png" /> </template> format In case you want to serve images in a specific format, use this prop. <NuxtImg format="webp" src="/nuxt-icon.png" ... /> Available formats are webp, avif, jpeg, jpg, png, gif and svg. If the format is not specified, it will respect the default image format. quality The quality for the generated image(s). <NuxtImg src="/nuxt.jpg" quality="80" width="200" height="100" /> fit The fit property specifies the size of the images. There are five standard values you can use with this property. cover: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit contain: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. fill: Ignore the aspect ratio of the input and stretch to both provided dimensions. inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. <NuxtImg fit="cover" src="/nuxt-icon.png" width="200" height="100" /> Some providers support other values. modifiers In addition to the standard modifiers, each provider might have its own additional modifiers. Because these modifiers depend on the provider, refer to its documentation to know what can be used. Using the modifiers prop lets you use any of these transformations. Example: <NuxtImg provider="cloudinary" src="/remote/nuxt-org/blog/going-full-static/main.png" width="300" height="169" :modifiers="{ roundCorner: '0:100' }" /> preload In case you want to preload the image, use this prop. This will place a corresponding link tag in the page's head. <NuxtImg preload src="/nuxt-icon.png" /> loading This is a native attribute that provides a hint to the browser on how to handle the loading of an image which is outside the viewport. It is supported by the latest version of all major browsers since March 2022. Set loading="lazy" to defer loading of an image until it appears in the viewport. <NuxtImg src="/nuxt-icon.png" loading="lazy" /> nonce This is a native global attribute that defines a cryptographic nonce (number used once) that can be used by Content Security Policy to determine whether or not a given fetch will be allowed to proceed for a given element. Providing a nonce allows you to avoid using the CSP unsafe-inline directive, which would allowlist all inline script or styles. <NuxtImg src="/nuxt-icon.png" :nonce="nonce" /> <script lang="ts" setup> // useNonce is not provided by nuxt/image but might be // provided by another module, for example nuxt-security const nonce = useNonce() </script> Events Native events emitted by the <img> element contained by <NuxtImg> and <NuxtPicture> components are re-emitted and can be listened to. Example: Listen to the native onLoad event from <NuxtImg> <NuxtImg src="/images/colors.jpg" width="500" height="500" @load="doSomethingOnLoad" /> Contributing We can never thank you enough for your contributions. ❤️ <NuxtPicture> Discover how to use and configure the Nuxt Picture component.
<NuxtImg> - Nuxt Image
https://image.nuxt.com/usage/nuxt-picture
Usage <NuxtPicture> Source Discover how to use and configure the Nuxt Picture component. <NuxtPicture> is a drop-in replacement for the native <picture> tag. Usage of <NuxtPicture> is almost identical to <NuxtImg> but also allows serving modern formats like webp when possible. Learn more about the <picture> tag on MDN. Props See props supported by<NuxtImg> format Format on pictures can be used to serve images in multiple formats. A legacy format will be generated automatically. So in the example below avif, webp and png would be generated. They will be added in the same order they are added to the format attribute. <NuxtPicture format="avif,webp" src="/nuxt-icon.png" ... /> Available formats are webp, avif, jpeg, jpg, png and gif. If the format is not specified, it will respect the default image format. legacyFormat Format used for fallback. Default is conditional: If original format supports transparency (png, webp and gif), png is used for fallback Otherwise jpeg is used for fallback imgAttrs Allows you to set additional HTML-attributes on the img element. Example: <NuxtPicture src="/nuxt-icon.png" :imgAttrs="{id:'my-id', class:'my-class', style:'display:block', 'data-my-data': 'my-value'}" /> <NuxtImg> Discover how to use and configure the Nuxt Image component. useImage() A Vue composable that returns a helper function to generate optimized image URLs.
<NuxtPicture> - Nuxt Image
https://image.nuxt.com/get-started/providers
Get Started Providers Nuxt Image supports multiple providers for high performances. Introduction to providers Providers are integrations between Nuxt Image and third-party image transformation services. Each provider is responsible for generating correct URLs for that image transformation service. Nuxt Image can be configured to work with any external image transformation service. Checkout sidebar for list of preconfigured providers. If you are looking for a specific provider that is not already supported, you can create your own provider. Nuxt Image will automatically optimize <NuxtImg> or <NuxtPicture> sources and accepts all options for specified target, except for modifiers that are specific to other providers. Default Provider The default optimizer and provider for Nuxt Image is ipx. Either option can be used without any configuration. Local Images Images should be stored in the public/ directory of your project. For example, when using <NuxtImg src="/nuxt-icon.png" />, it should be placed in public/ folder under the path public/nuxt-icon.png. For more information, you can learn more about the public directory. Image stored in the assets/ directory are not proccessed with Nuxt Image because those images are managed by webpack. Remote Images Using default provider, you can also optimize external URLs. For this, you need to add them to domains option. Environment Detection You can set default provider using NUXT_IMAGE_PROVIDER environment variable. Providers detected automatically: Vercel Custom Provider It is possible to define your own provider, learn more how to create a custom provider. Configuration Nuxt Image is configured with sensible defaults. Contributing We can never thank you enough for your contributions. ❤️
Providers - Nuxt Image
https://image.nuxt.com/get-started/configuration
Get Started Configuration Nuxt Image is configured with sensible defaults. To configure the image module and customize its behavior, you can use the image property in your nuxt.config: nuxt.config.ts export default defineNuxtConfig({ image: { // Options } }) inject By default Nuxt Image v1 adopts a composable approach. If you do not use the components no additional code will be added to your bundle. But if you wish to globally initialize an $img helper that will be available throughout your application, you can do so. nuxt.config.ts export default defineNuxtConfig({ image: { inject: true } }) quality The quality for the generated image(s). You can also override this option at the component level by using the quality prop. nuxt.config.ts export default defineNuxtConfig({ image: { quality: 80, } }) format Default: ['webp'] You can use this option to configure the default format for your images used by <NuxtPicture>. The available formats are webp, avif, jpeg, jpg, png, and gif. The order of the formats is important, as the first format that is supported by the browser will be used. You can pass multiple values like ['avif', 'webp']. You can also override this option at the component level by using the format prop. nuxt.config.ts export default defineNuxtConfig({ image: { format: ['webp'] } }) screens List of predefined screen sizes. These sizes will be used to generate resized and optimized versions of an image (for example, with the sizes modifier). nuxt.config.ts export default defineNuxtConfig({ image: { // The screen sizes predefined by `@nuxt/image`: screens: { 'xs': 320, 'sm': 640, 'md': 768, 'lg': 1024, 'xl': 1280, 'xxl': 1536, '2xl': 1536 }, } }) domains To enable image optimization on an external website, specify which domains are allowed to be optimized. This option will be used to detect whether a remote image should be optimized or not. This is needed to ensure that external urls can't be abused. nuxt.config.ts export default defineNuxtConfig({ image: { domains: ['nuxtjs.org'] } }) presets Presets are collections of pre-defined configurations for your projects. Presets will help you to unify images all over your project. nuxt.config.ts index.vue export default defineNuxtConfig({ image: { presets: { avatar: { modifiers: { format: 'jpg', width: 50, height: 50 } } } } }) providers In order to create and use a custom provider, you need to use the providers option and define your custom providers. nuxt.config.ts index.vue export default defineNuxtConfig({ image: { providers: { random: { provider: '~/providers/random', options: {} } } } }) provider Default: ipx (or ipxStatic if used with a static nitro preset, such as if you are running nuxt generate) We can specify default provider to be used when not specified in component or when calling $img. nuxt.config.ts export default defineNuxtConfig({ image: { provider: 'twicpics', twicpics: { baseURL: 'https://nuxt-demo.twic.pics' } } }) modifiers You can set default modifiers for the selected provider. nuxt.config.ts export default defineNuxtConfig({ image: { provider: 'cloudinary', cloudinary: { baseURL: 'https://res.cloudinary.com/<company>/image/fetch/', modifiers: { effect: 'sharpen:100', quality: 'auto:best', } } } }) densities Default: [1, 2] Specify a value to work with devicePixelRatio > 1 (these are devices with retina display and others). You must specify for which devicePixelRatio values you want to adapt images. You can read more about devicePixelRatio on MDN. nuxt.config.ts export default defineNuxtConfig({ image: { densities: [1, 2, 3], } }) dir Default: public This option allows you to specify the location of the source images when using the ipx or ipxStatic provider. For example you might want the source images in assets/images directory rather than the default public directory so the source images don't get copied into dist and deployed: nuxt.config.ts export default defineNuxtConfig({ image: { dir: 'assets/images' } }) Notes: For ipxStatic provider, if images weren't crawled during generation (unreachable modals, pages or dynamic runtime size), changing dir from public causes 404 errors. For ipx provider, make sure to deploy customized dir as well. For some providers (like vercel), using a directory other than public/ for assets is not supported since resizing happens at runtime (instead of build/generate time) and source fetched from the public/ directory (deployment URL) alias This option allows you to specify aliases for src. When using the default ipx provider, URL aliases are shortened on the server-side. This is especially useful for optimizing external URLs and not including them in HTML. When using other providers, aliases are resolved in runtime and included in HTML. (only the usage is simplified) Example: nuxt.config.ts export default defineNuxtConfig({ image: { domains: [ 'images.unsplash.com' ], alias: { unsplash: 'https://images.unsplash.com' } } }) Before using alias: <NuxtImg src="https://images.unsplash.com/<id>" /> Generates: <img src="/_ipx/https://images.unsplash.com/<id>"> After using alias: <NuxtImg src="/unsplash/<id>" /> Generates: <img src="/_ipx/unsplash/<id>" /> Both usage and output are simplified! Installation Using image module in your Nuxt project is only one command away. Providers Nuxt Image supports multiple providers for high performances.
Configuration - Nuxt Image
https://image.nuxt.com/get-started/installation
Get Started Installation Using image module in your Nuxt project is only one command away. You are reading the v1 documentation compatible with Nuxt 3. Checkout v0.image.nuxtjs.org for Nuxt 2 compatible version. (Announcement). Add @nuxt/image dependency to your project: pnpm yarn npm pnpm add @nuxt/image Add it to modules in your nuxt.config: nuxt.config.ts export default defineNuxtConfig({ modules: [ '@nuxt/image', ] }) You can now start using <NuxtImg> and <NuxtPicture> components in your application ✨ Configuration Add an image section in your nuxt.config: nuxt.config.ts image: { // Options } Checkout the image configuration for all available options and features to customize. Edge Channel After each commit is merged into the main branch of @nuxt/image and passing all tests, we trigger an automated npm release using Github Actions publishing a @nuxt/image-edge package. You can opt in to use this release channel and avoid waiting for the next release and helping the module by beta testing changes. The build and publishing method and quality of edge releases are the same as stable ones. The only difference is that you should often check the GitHub repository for updates. There is a slight chance of regressions not being caught during the review process and by the automated tests. Therefore, we internally use this channel to double-check everything before each release. Opting into the edge channel Update @nuxt/image dependency inside package.json: package.json { "devDependencies": { - "@nuxt/image": "^1.0.0" + "@nuxt/image": "npm:@nuxt/image-edge@latest" } } Remove lockfile (package-lock.json, yarn.lock, or pnpm-lock.yaml) and reinstall dependencies. Opting out from the edge channel Update @nuxt/image dependency inside package.json: package.json { "devDependencies": { - "@nuxt/image": "npm:@nuxt/image-edge@latest" + "@nuxt/image": "^1.0.0" } } Remove lockfile (package-lock.json, yarn.lock, or pnpm-lock.yaml) and reinstall dependencies. Troubleshooting If an error occurs during installation: Ensure using LTS version of NodeJS (NodeJS Download page) Try to upgrade to latest versions: pnpm yarn npm pnpm up @nuxt/image Try recreating lock-file: npx nuxt@latest upgrade --force If there is still an error related to sharp and node-gyp, it is is probably becase your OS architecture or NodeJS version is not included in pre-built binaries and needs to built from source (for example, this sometimes occurs on Apple M1). Checkout node-gyp for install requirements. If none of the above worked, please open an issue and include error trace, OS, Node version and the package manager used for installing.   Configuration Nuxt Image is configured with sensible defaults.
Installation - Nuxt Image
https://nuxt.com/docs/api/utils/dollarfetch
Utils $fetch Source Nuxt uses ofetch to expose globally the $fetch helper for making HTTP requests. Nuxt uses ofetch to expose globally the $fetch helper for making HTTP requests within your Vue app or API routes. During server-side rendering, calling $fetch to fetch your internal API routes will directly call the relevant function (emulating the request), saving an additional API call. Using $fetch in components without wrapping it with useAsyncData causes fetching the data twice: initially on the server, then again on the client-side during hydration, because $fetch does not transfer state from the server to the client. Thus, the fetch will be executed on both sides because the client has to get the data again. We recommend to use useFetch or useAsyncData + $fetch to prevent double data fetching when fetching the component data. app.vue <script setup lang="ts"> // During SSR data is fetched twice, once on the server and once on the client. const dataTwice = await $fetch('/api/item') // During SSR data is fetched only on the server side and transferred to the client. const { data } = await useAsyncData('item', () => $fetch('/api/item')) // You can also useFetch as shortcut of useAsyncData + $fetch const { data } = await useFetch('/api/item') </script> Read more in Docs > Getting Started > Data Fetching. You can use $fetch for any method that are executed only on client-side. pages/contact.vue <script setup lang="ts"> function contactForm() { $fetch('/api/contact', { method: 'POST', body: { hello: 'world '} }) } </script> <template> <button @click="contactForm">Contact</button> </template> $fetch is the preferred way to make HTTP calls in Nuxt instead of @nuxt/http and @nuxtjs/axios that are made for Nuxt 2. useState The useState composable creates a reactive and SSR-friendly shared state. abortNavigation abortNavigation is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.
$fetch · Nuxt Utils
https://nuxt.com/docs/bridge/overview
Upgrade Guide Migrate to Nuxt Bridge Overview Reduce the differences with Nuxt 3 and reduce the burden of migration to Nuxt 3. If you're starting a fresh Nuxt 3 project, please skip this section and go to Nuxt 3 Installation. Nuxt Bridge provides identical features to Nuxt 3 (docs) but there are some limitations, notably that useAsyncData and useFetch composables are not available. Please read the rest of this page for details. Bridge is a forward-compatibility layer that allows you to experience many of the new Nuxt 3 features by simply installing and enabling a Nuxt module. Using Nuxt Bridge, you can make sure your project is (almost) ready for Nuxt 3 and you can gradually proceed with the transition to Nuxt 3. First Step Upgrade Nuxt 2 Make sure your dev server (nuxt dev) isn't running, remove any package lock files (package-lock.json and yarn.lock), and install the latest Nuxt 2 version: package.json - "nuxt": "^2.16.3" + "nuxt": "^2.17.0" Then, reinstall your dependencies: yarn npm yarn install Once the installation is complete, make sure both development and production builds are working as expected before proceeding. Install Nuxt Bridge Install @nuxt/bridge-edge as a development dependency: Yarn npm yarn add --dev @nuxt/bridge@npm:@nuxt/bridge-edge Update nuxt.config Please make sure to avoid any CommonJS syntax such as module.exports, require or require.resolve in your config file. It will soon be deprecated and unsupported. You can use static import, dynamic import() and export default instead. Using TypeScript by renaming to nuxt.config.ts is also possible and recommended. nuxt.config.ts import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: false }) Update Commands The nuxt command should now be changed to the nuxt2 command. { "scripts": { - "dev": "nuxt", + "dev": "nuxt2", - "build": "nuxt build", + "build": "nuxt2 build", - "start": "nuxt start", + "start": "nuxt2 start" } } Try running nuxt2 once here. You will see that the application works as before. (If 'bridge' is set to false, your application will operate without any changes as before.) Upgrade Steps With Nuxt Bridge, the migration to Nuxt 3 can proceed in steps. The below Upgrade Steps does not need to be done all at once. TypeScript Migrate Legacy Composition API Plugins and Middleware Migrate New Composition API Meta Tags Runtime Config Nitro Vite Migrate from CommonJS to ESM Nuxt 3 natively supports TypeScript and ECMAScript Modules. Please check Native ES Modules for more info and upgrading. Releases Discover the latest releases of Nuxt & Nuxt official modules. TypeScript Learn how to use TypeScript with Nuxt Bridge.
Migrate to Nuxt Bridge: Overview
https://nuxt.com/docs/api/composables/use-server-seo-meta
Composables useServerSeoMeta Source The useServerSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support. Just like useSeoMeta, useServerSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support. Read more in Docs > API > Composables > Use Seo Meta. In most instances, the meta doesn't need to be reactive as robots will only scan the initial load. So we recommend using useServerSeoMeta as a performance-focused utility that will not do anything (or return a head object) on the client. app.vue <script setup lang="ts"> useServerSeoMeta({ robots: 'index, follow' }) </script> Parameters are exactly the same as with useSeoMeta Read more in Docs > Getting Started > Seo Meta. useSeoMeta The useSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support. useState The useState composable creates a reactive and SSR-friendly shared state.
useServerSeoMeta · Nuxt Composables
https://nuxt.com/docs/api/advanced/hooks
Advanced Lifecycle Hooks Nuxt provides a powerful hooking system to expand almost every aspect using hooks. Read more in Docs > Guide > Going Further > Hooks. App Hooks (runtime) Check the app source code for all available hooks. Hook Arguments Environment Description app:created vueApp Server & Client Called when initial vueApp instance is created. app:error err Server & Client Called when a fatal error occurs. app:error:cleared { redirect? } Server & Client Called when a fatal error occurs. app:data:refresh keys? Server & Client (internal) vue:setup - Server & Client (internal) vue:error err, target, info Server & Client Called when a vue error propagates to the root component. Learn More. app:rendered renderContext Server Called when SSR rendering is done. app:redirected - Server Called before SSR redirection. app:beforeMount vueApp Client Called before mounting the app, called only on client side. app:mounted vueApp Client Called when Vue app is initialized and mounted in browser. app:suspense:resolve appComponent Client On Suspense resolved event. link:prefetch to Client Called when a <NuxtLink> is observed to be prefetched. page:start pageComponent? Client Called on Suspense pending event. page:finish pageComponent? Client Called on Suspense resolved event. page:transition:finish pageComponent? Client After page transition onAfterLeave event. Nuxt Hooks (build time) Check the schema source code for all available hooks. Hook Arguments Description kit:compatibility compatibility, issues Allows extending compatibility checks. ready nuxt Called after Nuxt initialization, when the Nuxt instance is ready to work. close nuxt Called when Nuxt instance is gracefully closing. restart { hard?: boolean } To be called to restart the current Nuxt instance. modules:before - Called during Nuxt initialization, before installing user modules. modules:done - Called during Nuxt initialization, after installing user modules. app:resolve app Called after resolving the app instance. app:templates app Called during NuxtApp generation, to allow customizing, modifying or adding new files to the build directory (either virtually or to written to .nuxt). app:templatesGenerated app Called after templates are compiled into the virtual file system (vfs). build:before - Called before Nuxt bundle builder. build:done - Called after Nuxt bundle builder is complete. build:manifest manifest Called during the manifest build by Vite and webpack. This allows customizing the manifest that Nitro will use to render <script> and <link> tags in the final HTML. builder:generateApp options Called before generating the app. builder:watch event, path Called at build time in development when the watcher spots a change to a file or directory in the project. pages:extend pages Called after pages routes are resolved. server:devHandler handler Called when the dev middleware is being registered on the Nitro dev server. imports:sources presets Called at setup allowing modules to extend sources. imports:extend imports Called at setup allowing modules to extend imports. imports:context context Called when the unimport context is created. imports:dirs dirs Allows extending import directories. components:dirs dirs Called within app:resolve allowing to extend the directories that are scanned for auto-importable components. components:extend components Allows extending new components. nitro:config nitroConfig Called before initializing Nitro, allowing customization of Nitro's configuration. nitro:init nitro Called after Nitro is initialized, which allows registering Nitro hooks and interacting directly with Nitro. nitro:build:before nitro Called before building the Nitro instance. nitro:build:public-assets nitro Called after copying public assets. Allows modifying public assets before Nitro server is built. prerender:routes ctx Allows extending the routes to be pre-rendered. build:error error Called when an error occurs at build time. prepare:types options Called before Nuxi writes .nuxt/tsconfig.json and .nuxt/nuxt.d.ts, allowing addition of custom references and declarations in nuxt.d.ts, or directly modifying the options in tsconfig.json listen listenerServer, listener Called when the dev server is loading. schema:extend schemas Allows extending default schemas. schema:resolved schema Allows extending resolved schema. schema:beforeWrite schema Called before writing the given schema. schema:written - Called after the schema is written. vite:extend viteBuildContext Allows to extend Vite default context. vite:extendConfig viteInlineConfig, env Allows to extend Vite default config. vite:configResolved viteInlineConfig, env Allows to read the resolved Vite config. vite:serverCreated viteServer, env Called when the Vite server is created. vite:compiled - Called after Vite server is compiled. webpack:config webpackConfigs Called before configuring the webpack compiler. webpack:configResolved webpackConfigs Allows to read the resolved webpack config. webpack:compile options Called right before compilation. webpack:compiled options Called after resources are loaded. webpack:change shortPath Called on change on WebpackBar. webpack:error - Called on done if has errors on WebpackBar. webpack:done - Called on allDone on WebpackBar. webpack:progress statesArray Called on progress on WebpackBar. Nitro App Hooks (runtime, server-side) See Nitro for all available hooks. Hook Arguments Description Types render:response response, { event } Called before sending the response. response, event render:html html, { event } Called before constructing the HTML. html, event render:island islandResponse, { event, islandContext } Called before constructing the island HTML. islandResponse, event, islandContext close - Called when Nitro is closed. - error error, { event? } Called when an error occurs. error, event request event Called when a request is received. event beforeResponse event, { body } Called before sending the response. event, unknown afterResponse event, { body } Called after sending the response. event, unknown Examples Examples of Nuxt Kit utilities in use. Import meta Understand where your code is running using `import.meta`.
Lifecycle Hooks · Nuxt API
https://nuxt.com/docs/bridge/configuration
Upgrade Guide Migrate to Nuxt Bridge Configuration Learn how to configure Nuxt Bridge to your own needs. Feature Flags You can optionally disable some features from bridge or opt-in to less stable ones. In normal circumstances, it is always best to stick with defaults! You can check bridge/src/module.ts for latest defaults. nuxt.config.ts import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { // -- Opt-in features -- // Use Vite as the bundler instead of webpack 4 // vite: true, // Enable Nuxt 3 compatible useHead // meta: true, // -- Default features -- // Use legacy server instead of Nitro // nitro: false, // Disable Nuxt 3 compatible `nuxtApp` interface // app: false, // Disable Composition API support // capi: false, // ... or just disable legacy Composition API support // capi: { // legacy: false // }, // Do not transpile modules // transpile: false, // Disable <script setup> support // scriptSetup: false, // Disable composables auto importing // imports: false, // Do not warn about module incompatibilities // constraints: false }, vite: { // Config for Vite } }) Migration of each option router.base export default defineNuxtConfig({ - router: { - base: '/my-app/' - } + app: { + baseURL: '/my-app/' + } }) build.publicPath export default defineNuxtConfig({ - build: { - publicPath: 'https://my-cdn.net' - } + app: { + cdnURL: 'https://my-cdn.net' + } }) Vite Activate Vite to your Nuxt 2 application with Nuxt Bridge. Overview Nuxt 3 is a complete rewrite of Nuxt 2, and also based on a new set of underlying technologies.
Migrate to Nuxt Bridge: Configuration
https://nuxt.com/docs/bridge/vite
Upgrade Guide Migrate to Nuxt Bridge Vite Activate Vite to your Nuxt 2 application with Nuxt Bridge. When using vite, nitro must have been configured. Remove Modules Remove nuxt-vite: Bridge enables same functionality Update Config nuxt.config.ts import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { vite: true, nitro: true } }) Configuration nuxt.config.ts import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ vite: { // Config for Vite } }) Nitro Activate Nitro to your Nuxt 2 application with Nuxt Bridge. Configuration Learn how to configure Nuxt Bridge to your own needs.
Migrate to Nuxt Bridge: Vite
https://nuxt.com/docs/bridge/runtime-config
Upgrade Guide Migrate to Nuxt Bridge Runtime Config Nuxt provides a runtime config API to expose configuration and secrets within your application. When using runtimeConfig option, nitro must have been configured. Update Runtime Config Nuxt 3 approaches runtime config differently than Nuxt 2, using a new combined runtimeConfig option. First, you'll need to combine your publicRuntimeConfig and privateRuntimeConfig properties into a new one called runtimeConfig, with the public config within a key called public. // nuxt.config.js - privateRuntimeConfig: { - apiKey: process.env.NUXT_API_KEY || 'super-secret-key' - }, - publicRuntimeConfig: { - websiteURL: 'https://public-data.com' - } + runtimeConfig: { + apiKey: process.env.NUXT_API_KEY || 'super-secret-key', + public: { + websiteURL: 'https://public-data.com' + } + } This also means that when you need to access public runtime config, it's behind a property called public. If you use public runtime config, you'll need to update your code. // MyWidget.vue - <div>Website: {{ $config.websiteURL }}</div> + <div>Website: {{ $config.public.websiteURL }}</div> Meta Tags Learn how to migrate from Nuxt 2 to Nuxt Bridge new meta tags. Nitro Activate Nitro to your Nuxt 2 application with Nuxt Bridge.
Migrate to Nuxt Bridge: Runtime Config
https://nuxt.com/docs/bridge/meta
Upgrade Guide Migrate to Nuxt Bridge Meta Tags Learn how to migrate from Nuxt 2 to Nuxt Bridge new meta tags. If you need to access the component state with head, you should migrate to using useHead . If you need to use the Options API, there is a head() method you can use when you use defineNuxtComponent. Migration Set bridge.meta import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { meta: true, nitro: false // If migration to Nitro is complete, set to true } }) Update head properties In your nuxt.config, rename head to meta. (Note that objects no longer have a hid key for deduplication.) Nuxt 2 Nuxt 3 export default { head: { titleTemplate: '%s - Nuxt', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { hid: 'description', name: 'description', content: 'Meta description' } ] } } useHead Composables Nuxt Bridge provides a new Nuxt 3 meta API that can be accessed with a new useHead composable. <script setup lang="ts"> useHead({ title: 'My Nuxt App', }) </script> This useHead composable uses @unhead/vue under the hood (rather than vue-meta) to manipulate your <head>. We recommend not using the native Nuxt 2 head() properties in addition to useHead , as they may conflict. For more information on how to use this composable, see the docs. Options API <script> // if using options API `head` method you must use `defineNuxtComponent` export default defineNuxtComponent({ head (nuxtApp) { // `head` receives the nuxt app but cannot access the component instance return { meta: [{ name: 'description', content: 'This is my page description.' }] } } }) </script> Title Template If you want to use a function (for full control), then this cannot be set in your nuxt.config, and it is recommended instead to set it within your /layouts directory. layouts/default.vue <script setup lang="ts"> useHead({ titleTemplate: (titleChunk) => { return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'; } }) </script> New Composition API Nuxt Bridge implements composables compatible with Nuxt 3. Runtime Config Nuxt provides a runtime config API to expose configuration and secrets within your application.
Migrate to Nuxt Bridge: Meta Tags
https://nuxt.com/docs/bridge/nitro
Upgrade Guide Migrate to Nuxt Bridge Nitro Activate Nitro to your Nuxt 2 application with Nuxt Bridge. Remove Modules Remove @nuxt/nitro: Bridge injects same functionality Update Config nuxt.config.ts import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { nitro: true } }) Update Your Scripts You will also need to update your scripts within your package.json to reflect the fact that Nuxt will now produce a Nitro server as build output. Install Nuxi Install nuxi as a development dependency: yarn npm yarn add --dev nuxi Nuxi Nuxt 3 introduced the new Nuxt CLI command nuxi. Update your scripts as follows to leverage the better support from Nuxt Bridge: { "scripts": { - "dev": "nuxt", + "dev": "nuxi dev", - "build": "nuxt build", + "build": "nuxi build", - "start": "nuxt start", + "start": "nuxi preview" } } If nitro: false, use the nuxt2 command. Static Target If you have set target: 'static' in your nuxt.config then you need to ensure that you update your build script to be nuxi generate. package.json { "scripts": { "build": "nuxi generate" } } Server Target For all other situations, you can use the nuxi build command. package.json { "scripts": { "build": "nuxi build", "start": "nuxi preview" } } Exclude Built Nitro Folder From Git Add the folder .output to the .gitignore file. Ensure Everything Goes Well ✔️ Try with nuxi dev and nuxi build (or nuxi generate) to see if everything goes well. Runtime Config Nuxt provides a runtime config API to expose configuration and secrets within your application. Vite Activate Vite to your Nuxt 2 application with Nuxt Bridge.
Migrate to Nuxt Bridge: Nitro
https://nuxt.com/docs/bridge/nuxt3-compatible-api
Upgrade Guide Migrate to Nuxt Bridge New Composition API Nuxt Bridge implements composables compatible with Nuxt 3. By migrating from @nuxtjs/composition-api to the Nuxt 3 compatible API, there will be less rewriting when migrating to Nuxt 3. ssrRef and shallowSsrRef These two functions have been replaced with a new composable that works very similarly under the hood: useState. The key differences are that you must provide a key for this state (which Nuxt generated automatically for ssrRef and shallowSsrRef), and that it can only be called within a Nuxt 3 plugin (which is defined by defineNuxtPlugin) or a component instance. (In other words, you cannot use useState with a global/ambient context, because of the danger of shared state across requests.) - import { ssrRef } from '@nuxtjs/composition-api' - const ref1 = ssrRef('initialData') - const ref2 = ssrRef(() => 'factory function') + const ref1 = useState('ref1-key', () => 'initialData') + const ref2 = useState('ref2-key', () => 'factory function') // accessing the state console.log(ref1.value) Because the state is keyed, you can access the same state from multiple locations, as long as you are using the same key. You can read more about how to use this composable in the Nuxt 3 docs. ssrPromise This function has been removed, and you will need to find an alternative implementation if you were using it. If you have a use case for ssrPromise, please let us know via a discussion. onGlobalSetup This function has been removed, but its use cases can be met by using useNuxtApp or useState within defineNuxtPlugin. You can also run any custom code within the setup() function of a layout. - import { onGlobalSetup } from '@nuxtjs/composition-api' - export default () => { - onGlobalSetup(() => { + export default defineNuxtPlugin((nuxtApp) => { + nuxtApp.hook('vue:setup', () => { // ... }) - } + }) useStore In order to access Vuex store instance, you can use useNuxtApp().$store. - import { useStore } from '@nuxtjs/composition-api` + const { $store } = useNuxtApp() useContext and withContext You can access injected helpers using useNuxtApp. - import { useContext } from '@nuxtjs/composition-api` + const { $axios } = useNuxtApp() useNuxtApp() also provides a key called nuxt2Context which contains all the same properties you would normally access from Nuxt 2 context, but it's advised not to use this directly, as it won't exist in Nuxt 3. Instead, see if there is another way to access what you need. (If not, please raise a feature request or discussion.) wrapProperty This helper function is not provided any more but you can replace it with the following code: const wrapProperty = (property, makeComputed = true) => () => { const vm = getCurrentInstance().proxy return makeComputed ? computed(() => vm[property]) : vm[property] } useAsync and useFetch These two composables can be replaced with useLazyAsyncData and useLazyFetch, which are documented in the Nuxt 3 docs. Just like the previous @nuxtjs/composition-api composables, these composables do not block route navigation on the client-side (hence the 'lazy' part of the name). Note that the API is entirely different, despite similar sounding names. Importantly, you should not attempt to change the value of other variables outside the composable (as you may have been doing with the previous useFetch). The useLazyFetch must have been configured for Nitro. Migrating to the new composables from useAsync: <script setup> - import { useAsync } from '@nuxtjs/composition-api' - const posts = useAsync(() => $fetch('/api/posts')) + const { data: posts } = useLazyAsyncData('posts', () => $fetch('/api/posts')) + // or, more simply! + const { data: posts } = useLazyFetch('/api/posts') </script> Migrating to the new composables from useFetch: <script setup> - import { useFetch } from '@nuxtjs/composition-api' - const posts = ref([]) - const { fetch } = useFetch(() => { posts.value = await $fetch('/api/posts') }) + const { data: posts, refresh } = useLazyAsyncData('posts', () => $fetch('/api/posts')) + // or, more simply! + const { data: posts, refresh } = useLazyFetch('/api/posts') function updatePosts() { - return fetch() + return refresh() } </script> useMeta In order to interact with vue-meta, you may use useNuxt2Meta, which will work in Nuxt Bridge (but not Nuxt 3) and will allow you to manipulate your meta tags in a vue-meta-compatible way. <script setup> - import { useMeta } from '@nuxtjs/composition-api' useNuxt2Meta({ title: 'My Nuxt App', }) </script> You can also pass in computed values or refs, and the meta values will be updated reactively: <script setup> const title = ref('my title') useNuxt2Meta({ title, }) title.value = 'new title' </script> Be careful not to use both useNuxt2Meta() and the Options API head() within the same component, as behavior may be unpredictable. Nuxt Bridge also provides a Nuxt 3-compatible meta implementation that can be accessed with the useHead composable. <script setup> - import { useMeta } from '@nuxtjs/composition-api' useHead({ title: 'My Nuxt App', }) </script> You will also need to enable it explicitly in your nuxt.config: import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { meta: true } }) This useHead composable uses @unhead/vue under the hood (rather than vue-meta) to manipulate your <head>. Accordingly, it is recommended not to use both the native Nuxt 2 head() properties as well as useHead , as they may conflict. For more information on how to use this composable, see the Nuxt 3 docs. Explicit Imports Nuxt exposes every auto-import with the #imports alias that can be used to make the import explicit if needed: <script setup lang="ts"> import { ref, computed } from '#imports' const count = ref(1) const double = computed(() => count.value * 2) </script> Disabling Auto-imports If you want to disable auto-importing composables and utilities, you can set imports.autoImport to false in the nuxt.config file. nuxt.config.ts export default defineNuxtConfig({ imports: { autoImport: false } }) This will disable auto-imports completely but it's still possible to use explicit imports from #imports. Plugins and Middleware Learn how to migrate from Nuxt 2 to Nuxt Bridge new plugins and middleware. Meta Tags Learn how to migrate from Nuxt 2 to Nuxt Bridge new meta tags.
Migrate to Nuxt Bridge: New Composition API
https://nuxt.com/docs/api/utils/define-nuxt-component
Utils defineNuxtComponent Source defineNuxtComponent() is a helper function for defining type safe components with Options API. defineNuxtComponent() is a helper function for defining type safe Vue components using options API similar to defineComponent(). defineNuxtComponent() wrapper also adds support for asyncData and head component options. Using <script setup lang="ts"> is the recommended way of declaring Vue components in Nuxt 3. Read more in Docs > Getting Started > Data Fetching. asyncData() If you choose not to use setup() in your app, you can use the asyncData() method within your component definition: pages/index.vue <script lang="ts"> export default defineNuxtComponent({ async asyncData() { return { data: { greetings: 'hello world!' } } }, }) </script> head() If you choose not to use setup() in your app, you can use the head() method within your component definition: pages/index.vue <script lang="ts"> export default defineNuxtComponent({ head(nuxtApp) { return { title: 'My site' } }, }) </script> createError Create an error object with additional metadata. defineNuxtRouteMiddleware Create named route middleware using defineNuxtRouteMiddleware helper function.
defineNuxtComponent · Nuxt Utils
https://nuxt.com/docs/bridge/bridge-composition-api
Upgrade Guide Migrate to Nuxt Bridge Legacy Composition API Learn how to migrate to Composition API with Nuxt Bridge. Nuxt Bridge provides access to Composition API syntax. It is specifically designed to be aligned with Nuxt 3. Because of this, there are a few extra steps to take when enabling Nuxt Bridge, if you have been using the Composition API previously. Remove Modules Remove @vue/composition-api from your dependencies. Remove @nuxtjs/composition-api from your dependencies (and from your modules in nuxt.config). Using @vue/composition-api If you have been using just @vue/composition-api and not @nuxtjs/composition-api, then things are very straightforward. First, remove the plugin where you are manually registering the Composition API. Nuxt Bridge will handle this for you. - import Vue from 'vue' - import VueCompositionApi from '@vue/composition-api' - - Vue.use(VueCompositionApi) Otherwise, there is nothing you need to do. However, if you want, you can remove your explicit imports from @vue/composition-api and rely on Nuxt Bridge auto-importing them for you. Migrating from @nuxtjs/composition-api Nuxt Bridge implements the Composition API slightly differently from @nuxtjs/composition-api and provides different composables (designed to be aligned with the composables that Nuxt 3 provides). Because some composables have been removed and don't yet have a replacement, this will be a slightly more complicated process. Remove @nuxtjs/composition-api/module from your buildModules You don't have to immediately update your imports yet - Nuxt Bridge will automatically provide a 'shim' for most imports you currently have, to give you time to migrate to the new, Nuxt 3-compatible composables, with the following exceptions: withContext has been removed. See below. useStatic has been removed. There is no current replacement. Feel free to raise a discussion if you have a use case for this. reqRef and reqSsrRef, which were deprecated, have now been removed entirely. Follow the instructions below regarding ssrRef to replace this. Set bridge.capi import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { capi: true, nitro: false // If migration to Nitro is complete, set to true } }) For each other composable you are using from @nuxtjs/composition-api, follow the steps below. useFetch $fetchState and $fetch have been removed. const { - $fetch, - $fetchState, + fetch, + fetchState, } = useFetch(() => { posts.value = await $fetch('/api/posts') }) defineNuxtMiddleware This was a type-helper stub function that is now removed. Remove the defineNuxtMiddleware wrapper: - import { defineNuxtMiddleware } from '@nuxtjs/composition-api` - export default defineNuxtMiddleware((ctx) => {}) + export default (ctx) => {} For typescript support, you can use @nuxt/types: import type { Middleware } from '@nuxt/types' export default <Middleware> function (ctx) { } defineNuxtPlugin This was a type-helper stub function that is now removed. You may also keep using Nuxt 2-style plugins, by removing the function (as with defineNuxtMiddleware). Remove the defineNuxtPlugin wrapper: - import { defineNuxtPlugin } from '@nuxtjs/composition-api' - export default defineNuxtPlugin((ctx, inject) => {}) + export default (ctx, inject) => {} For typescript support, you can use @nuxt/types: import type { Plugin } from '@nuxt/types' export default <Plugin> function (ctx, inject) {} While this example is valid, Nuxt 3 introduces a new defineNuxtPlugin function that has a slightly different signature. Read more in Missing link. useRouter and useRoute Nuxt Bridge provides direct replacements for these composables via useRouter and useRoute. The only key difference is that useRoute no longer returns a computed property. - import { useRouter, useRoute } from '@nuxtjs/composition-api' const router = useRouter() const route = useRoute() - console.log(route.value.path) + console.log(route.path) TypeScript Learn how to use TypeScript with Nuxt Bridge. Plugins and Middleware Learn how to migrate from Nuxt 2 to Nuxt Bridge new plugins and middleware.
Migrate to Nuxt Bridge: Legacy Composition API
https://nuxt.com/docs/bridge/plugins-and-middleware
Upgrade Guide Migrate to Nuxt Bridge Plugins and Middleware Learn how to migrate from Nuxt 2 to Nuxt Bridge new plugins and middleware. New Plugins Format You can now migrate to the Nuxt 3 plugins API, which is slightly different in format from Nuxt 2. Plugins now take only one argument (nuxtApp). You can find out more in the docs. plugins/hello.ts export default defineNuxtPlugin(nuxtApp => { nuxtApp.provide('injected', () => 'my injected function') // now available on `nuxtApp.$injected` }) If you want to use the new Nuxt composables (such as useNuxtApp or useRuntimeConfig) within your plugins, you will need to use the defineNuxtPlugin helper for those plugins. Although a compatibility interface is provided via nuxtApp.vueApp you should avoid registering plugins, directives, mixins or components this way without adding your own logic to ensure they are not installed more than once, or this may cause a memory leak. New Middleware Format You can now migrate to the Nuxt 3 middleware API, which is slightly different in format from Nuxt 2. Middleware now take only two argument (to, from). You can find out more in the docs. export default defineNuxtRouteMiddleware((to) => { if (to.path !== '/') { return navigateTo('/') } }) Use of defineNuxtRouteMiddleware is not supported outside of the middleware directory. You can also use definePageMeta in Nuxt Bridge. But only for middleware and layout. Legacy Composition API Learn how to migrate to Composition API with Nuxt Bridge. New Composition API Nuxt Bridge implements composables compatible with Nuxt 3.
Migrate to Nuxt Bridge: Plugins and Middleware
https://nuxt.com/docs/bridge/typescript
Upgrade Guide Migrate to Nuxt Bridge TypeScript Learn how to use TypeScript with Nuxt Bridge. Remove Modules Remove @nuxt/typescript-build: Bridge enables same functionality Remove @nuxt/typescript-runtime and nuxt-ts: Nuxt 2 has built-in runtime support Set bridge.typescript import { defineNuxtConfig } from '@nuxt/bridge' export default defineNuxtConfig({ bridge: { typescript: true, nitro: false // If migration to Nitro is complete, set to true } }) Update tsconfig.json If you are using TypeScript, you can edit your tsconfig.json to benefit from auto-generated Nuxt types: tsconfig.json { + "extends": "./.nuxt/tsconfig.json", "compilerOptions": { ... } } As .nuxt/tsconfig.json is generated and not checked into version control, you'll need to generate that file before running your tests. Add nuxi prepare as a step before your tests, otherwise you'll see TS5083: Cannot read file '~/.nuxt/tsconfig.json' You may also need to add @vue/runtime-dom as a devDependency if you are struggling to get template type inference working with Volar. Keep in mind that all options extended from ./.nuxt/tsconfig.json will be overwritten by the options defined in your tsconfig.json. Overwriting options such as "compilerOptions.paths" with your own configuration will lead TypeScript to not factor in the module resolutions from ./.nuxt/tsconfig.json. This can lead to module resolutions such as #imports not being recognized.In case you need to extend options provided by ./.nuxt/tsconfig.json further, you can use the alias property within your nuxt.config. nuxi will pick them up and extend ./.nuxt/tsconfig.json accordingly. Overview Reduce the differences with Nuxt 3 and reduce the burden of migration to Nuxt 3. Legacy Composition API Learn how to migrate to Composition API with Nuxt Bridge.
Migrate to Nuxt Bridge: TypeScript
https://nuxt.com/docs/api/utils/clear-error
Utils clearError Source The clearError composable clears all handled errors. clearError Within your pages, components, and plugins, you can use clearError to clear all errors and redirect the user. Parameters: options?: { redirect?: string } You can provide an optional path to redirect to (for example, if you want to navigate to a 'safe' page). // Without redirect clearError() // With redirect clearError({ redirect: '/homepage' }) Errors are set in state using useError(). The clearError composable will reset this state and calls the app:error:cleared hook with the provided options. Read more in Docs > Getting Started > Error Handling. addRouteMiddleware addRouteMiddleware() is a helper function to dynamically add middleware in your application. clearNuxtData Delete cached data, error status and pending promises of useAsyncData and useFetch.
clearError · Nuxt Utils
https://nuxt.com/docs/api/utils/clear-nuxt-state
Utils clearNuxtState Source Delete the cached state of useState. This method is useful if you want to invalidate the state of useState. Type clearNuxtState (keys?: string | string[] | ((key: string) => boolean)): void Parameters keys: One or an array of keys that are used in useState to delete their cached state. If no keys are provided, all state will be invalidated. clearNuxtData Delete cached data, error status and pending promises of useAsyncData and useFetch. createError Create an error object with additional metadata.
clearNuxtState · Nuxt Utils
https://nuxt.com/docs/api/utils/define-nuxt-route-middleware
Utils defineNuxtRouteMiddleware Source Create named route middleware using defineNuxtRouteMiddleware helper function. Route middleware are stored in the middleware/ of your Nuxt application (unless set otherwise). Type defineNuxtRouteMiddleware(middleware: RouteMiddleware) => RouteMiddleware interface RouteMiddleware { (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard> } Parameters middleware Type: RouteMiddleware A function that takes two Vue Router's route location objects as parameters: the next route to as the first, and the current route from as the second. Learn more about available properties of RouteLocationNormalized in the Vue Router docs. Examples Showing Error Page You can use route middleware to throw errors and show helpful error messages: middleware/error.ts export default defineNuxtRouteMiddleware((to) => { if (to.params.id === '1') { throw createError({ statusCode: 404, statusMessage: 'Page Not Found' }) } }) The above route middleware will redirect a user to the custom error page defined in the ~/error.vue file, and expose the error message and code passed from the middleware. Redirection Use useState in combination with navigateTo helper function inside the route middleware to redirect users to different routes based on their authentication status: middleware/auth.ts export default defineNuxtRouteMiddleware((to, from) => { const auth = useState('auth') if (!auth.value.isAuthenticated) { return navigateTo('/login') } if (to.path !== '/dashboard') { return navigateTo('/dashboard') } }) Both navigateTo and abortNavigation are globally available helper functions that you can use inside defineNuxtRouteMiddleware. defineNuxtComponent defineNuxtComponent() is a helper function for defining type safe components with Options API. definePageMeta Define metadata for your page components.
defineNuxtRouteMiddleware · Nuxt Utils
https://nuxt.com/docs/api/utils/create-error
Utils createError Source Create an error object with additional metadata. You can use this function to create an error object with additional metadata. It is usable in both the Vue and Nitro portions of your app, and is meant to be thrown. Parameters err: { cause, data, message, name, stack, statusCode, statusMessage, fatal } In Vue App If you throw an error created with createError: on server-side, it will trigger a full-screen error page which you can clear with clearError. on client-side, it will throw a non-fatal error for you to handle. If you need to trigger a full-screen error page, then you can do this by setting fatal: true. Example pages/movies/[slug].vue <script setup lang="ts"> const route = useRoute() const { data } = await useFetch(`/api/movies/${route.params.slug}`) if (!data.value) { throw createError({ statusCode: 404, statusMessage: 'Page Not Found' }) } </script> In API Routes Use createError to trigger error handling in server API routes. Example export default eventHandler(() => { throw createError({ statusCode: 404, statusMessage: 'Page Not Found' }) }) Read more in Docs > Getting Started > Error Handling. clearNuxtState Delete the cached state of useState. defineNuxtComponent defineNuxtComponent() is a helper function for defining type safe components with Options API.
createError · Nuxt Utils
https://nuxt.com/docs/api/utils/clear-nuxt-data
Utils clearNuxtData Source Delete cached data, error status and pending promises of useAsyncData and useFetch. This method is useful if you want to invalidate the data fetching for another page. Type clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void Parameters keys: One or an array of keys that are used in useAsyncData to delete their cached data. If no keys are provided, all data will be invalidated. clearError The clearError composable clears all handled errors. clearNuxtState Delete the cached state of useState.
clearNuxtData · Nuxt Utils
https://nuxt.com/docs/api/composables/use-seo-meta
Composables useSeoMeta Source The useSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support. This helps you avoid common mistakes, such as using name instead of property, as well as typos - with over 100+ meta tags fully typed. This is the recommended way to add meta tags to your site as it is XSS safe and has full TypeScript support. Read more in Docs > Getting Started > Seo Meta. Usage app.vue <script setup lang="ts"> useSeoMeta({ title: 'My Amazing Site', ogTitle: 'My Amazing Site', description: 'This is my amazing site, let me tell you all about it.', ogDescription: 'This is my amazing site, let me tell you all about it.', ogImage: 'https://example.com/image.png', twitterCard: 'summary_large_image', }) </script> When inserting tags that are reactive, you should use the computed getter syntax (() => value): app.vue <script setup lang="ts"> const title = ref('My title') useSeoMeta({ title, description: () => `description: ${title.value}` }) </script> Parameters There are over 100 parameters. See the full list of parameters in the source code. Read more in Docs > Getting Started > Seo Meta. useRuntimeConfig Access runtime config variables with the useRuntimeConfig composable. useServerSeoMeta The useServerSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support.
useSeoMeta · Nuxt Composables
https://nuxt.com/docs/migration/server
Upgrade Guide Migrate to Nuxt 3 Server Learn how to migrate from Nuxt 2 to Nuxt 3 server. In a built Nuxt 3 application, there is no runtime Nuxt dependency. That means your site will be highly performant, and ultra-slim. But it also means you can no longer hook into runtime Nuxt server hooks. Read more in Docs > Guide > Concepts > Server Engine. Steps Remove the render key in your nuxt.config. Any files in ~/server/api and ~/server/middleware will be automatically registered; you can remove them from your serverMiddleware array. Update any other items in your serverMiddleware array to point to files or npm packages directly, rather than using inline functions. Read more in Docs > Guide > Directory Structure > Server. Read more in Docs > Guide > Going Further > Hooks #server Hooks Runtime. Build Tooling Learn how to migrate from Nuxt 2 to Nuxt 3 build tooling. Modules Learn how to migrate from Nuxt 2 to Nuxt 3 modules.
Migrate to Nuxt 3: Server
https://nuxt.com/docs/migration/component-options
Upgrade Guide Migrate to Nuxt 3 Component Options Learn how to migrate from Nuxt 2 components options to Nuxt 3 composables. asyncData and fetch Nuxt 3 provides new options for fetching data from an API. Isomorphic Fetch In Nuxt 2 you might use @nuxtjs/axios or @nuxt/http to fetch your data - or just the polyfilled global fetch. In Nuxt 3 you can use a globally available fetch method that has the same API as the Fetch API or $fetch method which is using unjs/ofetch. It has a number of benefits, including: It will handle 'smartly' making direct API calls if it's running on the server, or making a client-side call to your API if it's running on the client. (It can also handle calling third-party APIs.) Plus, it comes with convenience features including automatically parsing responses and stringifying data. You can read more about direct API calls or fetching data. Composables Nuxt 3 provides new composables for fetching data: useAsyncData and useFetch. They each have 'lazy' variants (useLazyAsyncData and useLazyFetch), which do not block client-side navigation. In Nuxt 2, you'd fetch your data in your component using a syntax similar to: export default { async asyncData({ params, $http }) { const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`) return { post } }, // or alternatively fetch () { this.post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`) } } Within your methods and templates, you could use the post variable similar how you'd use any other piece of data provided by your component. With Nuxt 3, you can perform this data fetching using composables in your setup() method or <script setup> tag: <script setup lang="ts"> // Define params wherever, through `defineProps()`, `useRoute()`, etc. const { data: post, refresh } = await useAsyncData('post', () => $fetch(`https://api.nuxtjs.dev/posts/${params.id}`) ) // Or instead - useFetch is a convenience wrapper around useAsyncData when you're just performing a simple fetch const { data: post, refresh } = await useFetch(`https://api.nuxtjs.dev/posts/${params.id}`) </script> You can now use post inside of your Nuxt 3 template, or call refresh to update the data. Despite the names, useFetch is not a direct replacement of the fetch() hook. Rather, useAsyncData replaces both hooks and is more customizable; it can do more than simply fetching data from an endpoint. useFetch is a convenience wrapper around useAsyncData for simply fetching data from an endpoint. Migration Replace the asyncData hook with useAsyncData or useFetch in your page/component. Replace the fetch hook with useAsyncData or useFetch in your component. head Read more in Docs > Migration > Meta. key You can now define a key within the definePageMeta compiler macro. pages/index.vue - <script> - export default { - key: 'index' - // or a method - // key: route => route.fullPath - } + <script setup> + definePageMeta({ + key: 'index' + // or a method + // key: route => route.fullPath + }) </script> layout Read more in Docs > Migration > Pages And Layouts. loading This feature is not yet supported in Nuxt 3. middleware Read more in Docs > Migration > Plugins And Middleware. scrollToTop This feature is not yet supported in Nuxt 3. If you want to overwrite the default scroll behavior of vue-router, you can do so in ~/app/router.options.ts (see docs) for more info. Similar to key, specify it within the definePageMeta compiler macro. pages/index.vue - <script> - export default { - scrollToTop: false - } + <script setup> + definePageMeta({ + scrollToTop: false + }) </script> transition Read more in Docs > Getting Started > Transitions. validate The validate hook in Nuxt 3 only accepts a single argument, the route. Just as in Nuxt 2, you can return a boolean value. If you return false and another match can't be found, this will mean a 404. You can also directly return an object with statusCode/statusMessage to respond immediately with an error (other matches will not be checked). pages/users/[id].vue - <script> - export default { - async validate({ params }) { - return /^\d+$/.test(params.id) - } - } + <script setup> + definePageMeta({ + validate: async (route) => { + const nuxtApp = useNuxtApp() + return /^\d+$/.test(route.params.id) + } + }) </script> watchQuery This is not supported in Nuxt 3. Instead, you can directly use a watcher to trigger refetching data. pages/users/[id].vue <script setup lang="ts"> const route = useRoute() const { data, refresh } = await useFetch('/api/user') watch(() => route.query, () => refresh()) </script> Pages and Layouts Learn how to migrate from Nuxt 2 to Nuxt 3 pages and layouts. Runtime Config Learn how to migrate from Nuxt 2 to Nuxt 3 runtime config.
Migrate to Nuxt 3: Component Options
https://nuxt.com/docs/migration/runtime-config
Upgrade Guide Migrate to Nuxt 3 Runtime Config Learn how to migrate from Nuxt 2 to Nuxt 3 runtime config. If you wish to reference environment variables within your Nuxt 3 app, you will need to use runtime config. When referencing these variables within your components, you will have to use the useRuntimeConfig composable in your setup method (or Nuxt plugin). In the server/ portion of your app, you can use useRuntimeConfig without any import. Read more in Docs > Guide > Going Further > Runtime Config. Migration Add any environment variables that you use in your app to the runtimeConfig property of the nuxt.config file. Migrate process.env to useRuntimeConfig throughout the Vue part of your app. nuxt.config.ts pages/index.vue server/api/hello.ts .env export default defineNuxtConfig({ runtimeConfig: { // Private config that is only available on the server apiSecret: '123', // Config within public will be also exposed to the client public: { apiBase: '/api' } }, }) Component Options Learn how to migrate from Nuxt 2 components options to Nuxt 3 composables. Build Tooling Learn how to migrate from Nuxt 2 to Nuxt 3 build tooling.
Migrate to Nuxt 3: Runtime Config
https://nuxt.com/docs/migration/overview
Upgrade Guide Migrate to Nuxt 3 Overview Nuxt 3 is a complete rewrite of Nuxt 2, and also based on a new set of underlying technologies. There are significant changes when migrating a Nuxt 2 app to Nuxt 3, although you can expect migration to become more straightforward as we move toward a stable release. This migration guide is under progress to align with the development of Nuxt 3. Some of these significant changes include: Moving from Vue 2 to Vue 3, including defaulting to the Composition API and script setup. Moving from webpack 4 and Babel to Vite or webpack 5 and esbuild. Moving from a runtime Nuxt dependency to a minimal, standalone server compiled with nitropack. If you need to remain on Nuxt 2, but want to benefit from Nuxt 3 features in Nuxt 2, you can alternatively check out how to get started with Bridge. Next Steps Learn about differences in configuration Configuration Learn how to configure Nuxt Bridge to your own needs. Configuration Learn how to migrate from Nuxt 2 to Nuxt 3 new configuration.
Migrate to Nuxt 3: Overview
https://nuxt.com/docs/migration/bundling
Upgrade Guide Migrate to Nuxt 3 Build Tooling Learn how to migrate from Nuxt 2 to Nuxt 3 build tooling. We use the following build tools by default: Vite or webpack Rollup PostCSS esbuild For this reason, most of your previous build configuration in nuxt.config will now be ignored, including any custom babel configuration. If you need to configure any of Nuxt's build tools, you can do so in your nuxt.config, using the new top-level vite, webpack and postcss keys. In addition, Nuxt ships with TypeScript support. Read more in Docs > Guide > Concepts > Typescript. Steps Remove @nuxt/typescript-build and @nuxt/typescript-runtime from your dependencies and modules. Remove any unused babel dependencies from your project. Remove any explicit core-js dependencies. Migrate require to import. Runtime Config Learn how to migrate from Nuxt 2 to Nuxt 3 runtime config. Server Learn how to migrate from Nuxt 2 to Nuxt 3 server.
Migrate to Nuxt 3: Build Tooling
https://nuxt.com/docs/api/composables/use-router
Composables useRouter Source The useRouter composable returns the router instance. pages/index.vue <script setup> const router = useRouter() </script> If you only need the router instance within your template, use $router: pages/index.vue <template> <button @click="$router.back()">Back</button> </template> If you have a pages/ directory, useRouter is identical in behavior to the one provided by vue-router. Read vue-router documentation about the Router interface. Basic Manipulation addRoute(): Add a new route to the router instance. parentName can be provided to add new route as the child of an existing route. removeRoute(): Remove an existing route by its name. getRoutes(): Get a full list of all the route records. hasRoute(): Checks if a route with a given name exists. resolve(): Returns the normalized version of a route location. Also includes an href property that includes any existing base. Example const router = useRouter() router.addRoute({ name: 'home', path: '/home', component: Home }) router.removeRoute('home') router.getRoutes() router.hasRoute('home') router.resolve({ name: 'home' }) router.addRoute() adds route details into an array of routes and it is useful while building Nuxt plugins while router.push() on the other hand, triggers a new navigation immediately and it is useful in pages, Vue components and composable. Based on History API back(): Go back in history if possible, same as router.go(-1). forward(): Go forward in history if possible, same as router.go(1). go(): Move forward or backward through the history without the hierarchical restrictions enforced in router.back() and router.forward(). push(): Programmatically navigate to a new URL by pushing an entry in the history stack. It is recommended to use navigateTo instead. replace(): Programmatically navigate to a new URL by replacing the current entry in the routes history stack. It is recommended to use navigateTo instead. Example const router = useRouter() router.back() router.forward() router.go(3) router.push({ path: "/home" }) router.replace({ hash: "#bio" }) Read more about the browser's History API. Navigation Guards useRouter composable provides afterEach, beforeEach and beforeResolve helper methods that acts as navigation guards. However, Nuxt has a concept of route middleware that simplifies the implementation of navigation guards and provides a better developer experience. Read more in Docs > Guide > Directory Structure > Middleware. Promise and Error Handling isReady(): Returns a Promise that resolves when the router has completed the initial navigation. onError: Adds an error handler that is called every time a non caught error happens during navigation. Read more in Vue Router Docs. Universal Router Instance If you do not have a pages/ folder, then useRouter will return a universal router instance with similar helper methods, but be aware that not all features may be supported or behave in exactly the same way as with vue-router. useRoute The useRoute composable returns the current route. useRuntimeConfig Access runtime config variables with the useRuntimeConfig composable.
useRouter · Nuxt Composables
https://nuxt.com/docs/api/components/client-only
Components <ClientOnly> Source Render components only in client-side with the <ClientOnly> component. The <ClientOnly> component renders its slot only in client-side. To import a component only on the client, register the component in a client-side only plugin. Props placeholderTag | fallbackTag: specify a tag to be rendered server-side. placeholder | fallback: specify a content to be rendered server-side. <template> <div> <Sidebar /> <ClientOnly fallback-tag="span" fallback="Loading comments..."> <Comment /> </ClientOnly> </div> </template> Slots #fallback: specify a content to be displayed server-side. <template> <div> <Sidebar /> <ClientOnly> <!-- ... --> <template #fallback> <!-- this will be rendered on server side --> <p>Loading comments...</p> </template> </ClientOnly> </div> </template> Nightly Release Channel The nightly release channel allows using Nuxt built directly from the latest commits to the repository. <NuxtClientFallback> Nuxt provides the <NuxtClientFallback> component to render its content on the client if any of its children trigger an error in SSR
<ClientOnly> · Nuxt Components
https://nuxt.com/docs/examples/experimental/wasm
Examples Experimental WASM This example demonstrates the server-side support of WebAssembly in Nuxt 3. Loading Sandbox... Use Custom Fetch Composable This example shows a convenient wrapper for the useFetch composable from nuxt. It allows you to customize the fetch request with default values and user authentication token.
WASM · Nuxt Examples
https://nuxt.com/docs/migration/pages-and-layouts
Upgrade Guide Migrate to Nuxt 3 Pages and Layouts Learn how to migrate from Nuxt 2 to Nuxt 3 pages and layouts. app.vue Nuxt 3 provides a central entry point to your app via ~/app.vue. If you don't have an app.vue file in your source directory, Nuxt will use its own default version. This file is a great place to put any custom code that needs to be run once when your app starts up, as well as any components that are present on every page of your app. For example, if you only have one layout, you can move this to app.vue instead. Read more in Docs > Guide > Directory Structure > App. Read and edit a live example in Docs > Examples > Hello World. Migration Consider creating an app.vue file and including any logic that needs to run once at the top-level of your app. You can check out an example here. Layouts If you are using layouts in your app for multiple pages, there is only a slight change required. In Nuxt 2, the <Nuxt> component is used within a layout to render the current page. In Nuxt 3, layouts use slots instead, so you will have to replace that component with a <slot />. This also allows advanced use cases with named and scoped slots. Read more about layouts. You will also need to change how you define the layout used by a page using the definePageMeta compiler macro. Layouts will be kebab-cased. So layouts/customLayout.vue becomes custom-layout when referenced in your page. Migration Replace <Nuxt /> with <slot /> layouts/custom.vue <template> <div id="app-layout"> <main> - <Nuxt /> + <slot /> </main> </div> </template> Use definePageMeta to select the layout used by your page. pages/index.vue <script> + definePageMeta({ + layout: 'custom' + }) - export default { - layout: 'custom' - } </script> Move ~/layouts/_error.vue to ~/error.vue. See the error handling docs. If you want to ensure that this page uses a layout, you can use <NuxtLayout> directly within error.vue: error.vue <template> <div> <NuxtLayout name="default"> <!-- --> </NuxtLayout> </div> </template> Pages Nuxt 3 ships with an optional vue-router integration triggered by the existence of a pages/ directory in your source directory. If you only have a single page, you may consider instead moving it to app.vue for a lighter build. Dynamic Routes The format for defining dynamic routes in Nuxt 3 is slightly different from Nuxt 2, so you may need to rename some of the files within pages/. Where you previously used _id to define a dynamic route parameter you now use [id]. Where you previously used _.vue to define a catch-all route, you now use [...slug].vue. Nested Routes In Nuxt 2, you will have defined any nested routes (with parent and child components) using <Nuxt> and <NuxtChild>. In Nuxt 3, these have been replaced with a single <NuxtPage> component. Page Keys and Keep-alive Props If you were passing a custom page key or keep-alive props to <Nuxt>, you will now use definePageMeta to set these options. Read more in Docs > Migration > Component Options. Page and Layout Transitions If you have been defining transitions for your page or layout directly in your component options, you will now need to use definePageMeta to set the transition. Since Vue 3, -enter and -leave CSS classes have been renamed. The style prop from <Nuxt> no longer applies to transition when used on <slot>, so move the styles to your -active class. Read more in Docs > Getting Started > Transitions. Migration Rename any pages with dynamic parameters to match the new format. Update <Nuxt> and <NuxtChild> to be <NuxtPage>. If you're using the Composition API, you can also migrate this.$route and this.$router to use useRoute and useRouter composables. Example: Dynamic Routes Nuxt 2 Nuxt 3 - URL: /users - Page: /pages/users/index.vue - URL: /users/some-user-name - Page: /pages/users/_user.vue - Usage: params.user - URL: /users/some-user-name/edit - Page: /pages/users/_user/edit.vue - Usage: params.user - URL: /users/anything-else - Page: /pages/users/_.vue - Usage: params.pathMatch Example: Nested Routes and definePageMeta Nuxt 2 Nuxt 3 <template> <div> <NuxtChild keep-alive :keep-alive-props="{ exclude: ['modal'] }" :nuxt-child-key="$route.slug" /> </div> </template> <script> export default { transition: 'page' // or { name: 'page' } } </script> <NuxtLink> Component Most of the syntax and functionality are the same for the global NuxtLink component. If you have been using the shortcut <NLink> format, you should update this to use <NuxtLink>. <NuxtLink> is now a drop-in replacement for all links, even external ones. You can read more about it, and how to extend it to provide your own link component. Read more in Docs > API > Components > Nuxt Link. Programmatic Navigation When migrating from Nuxt 2 to Nuxt 3, you will have to update how you programmatically navigate your users. In Nuxt 2, you had access to the underlying Vue Router with this.$router. In Nuxt 3, you can use the navigateTo() utility method which allows you to pass a route and parameters to Vue Router. Ensure to always await on navigateTo or chain its result by returning from functions. Nuxt 2 Nuxt 3 <script> export default { methods: { navigate(){ this.$router.push({ path: '/search', query: { name: 'first name', type: '1' } }) } } } </script> Plugins and Middleware Learn how to migrate from Nuxt 2 to Nuxt 3 plugins and middleware. Component Options Learn how to migrate from Nuxt 2 components options to Nuxt 3 composables.
Migrate to Nuxt 3: Pages and Layouts
https://nuxt.com/docs/migration/auto-imports
Upgrade Guide Migrate to Nuxt 3 Auto Imports Nuxt 3 adopts a minimal friction approach, meaning wherever possible components and composables are auto-imported. In the rest of the migration documentation, you will notice that key Nuxt and Vue utilities do not have explicit imports. This is not a typo; Nuxt will automatically import them for you, and you should get full type hinting if you have followed the instructions to use Nuxt's TypeScript support. Read more about auto imports Migration If you have been using @nuxt/components in Nuxt 2, you can remove components: true in your nuxt.config. If you had a more complex setup, then note that the component options have changed somewhat. See the components documentation for more information. You can look at .nuxt/types/components.d.ts and .nuxt/types/imports.d.ts to see how Nuxt has resolved your components and composable auto-imports. Configuration Learn how to migrate from Nuxt 2 to Nuxt 3 new configuration. Meta Tags Manage your meta tags, from Nuxt 2 to Nuxt 3.
Migrate to Nuxt 3: Auto Imports
https://nuxt.com/docs/migration/plugins-and-middleware
Upgrade Guide Migrate to Nuxt 3 Plugins and Middleware Learn how to migrate from Nuxt 2 to Nuxt 3 plugins and middleware. Plugins Plugins now have a different format, and take only one argument (nuxtApp). Nuxt 2 Nuxt 3 export default (ctx, inject) => { inject('injected', () => 'my injected function') }) Read more in Docs > Guide > Directory Structure > Plugins. Read more about the format of nuxtApp. Migration Migrate your plugins to use the defineNuxtPlugin helper function. Remove any entries in your nuxt.config plugins array that are located in your plugins/ folder. All files in this directory at the top level (and any index files in any subdirectories) will be automatically registered. Instead of setting mode to client or server, you can indicate this in the file name. For example, ~/plugins/my-plugin.client.ts will only be loaded on client-side. Route Middleware Route middleware has a different format. Nuxt 2 Nuxt 3 export default function ({ store, redirect }) { // If the user is not authenticated if (!store.state.authenticated) { return redirect('/login') } } Much like Nuxt 2, route middleware placed in your ~/middleware folder is automatically registered. You can then specify it by name in a component. However, this is done with definePageMeta rather than as a component option. navigateTo is one of a number of route helper functions. Read more in Docs > Guide > Directory Structure > Middleware. Migration Migrate your route middleware to use the defineNuxtRouteMiddleware helper function. Any global middleware (such as in your nuxt.config) can be placed in your ~/middleware folder with a .global extension, for example ~/middleware/auth.global.ts. Meta Tags Manage your meta tags, from Nuxt 2 to Nuxt 3. Pages and Layouts Learn how to migrate from Nuxt 2 to Nuxt 3 pages and layouts.
Migrate to Nuxt 3: Plugins and Middleware
https://nuxt.com/docs/migration/meta
Upgrade Guide Migrate to Nuxt 3 Meta Tags Manage your meta tags, from Nuxt 2 to Nuxt 3. Nuxt 3 provides several different ways to manage your meta tags: Through your nuxt.config. Through the useHead composable Through global meta components You can customize title, titleTemplate, base, script, noscript, style, meta, link, htmlAttrs and bodyAttrs. Nuxt currently uses vueuse/head to manage your meta tags, but implementation details may change. Read more in Docs > Getting Started > Seo Meta. Migration In your nuxt.config, rename head to meta. Consider moving this shared meta configuration into your app.vue instead. (Note that objects no longer have a hid key for deduplication.) If you need to access the component state with head, you should migrate to using useHead . You might also consider using the built-in meta-components. If you need to use the Options API, there is a head() method you can use when you use defineNuxtComponent. useHead Nuxt 2 Nuxt 3 <script> export default { data: () => ({ title: 'My App', description: 'My App Description' }) head () { return { title: this.title, meta: [{ hid: 'description', name: 'description', content: this.description }] } } } </script> Meta-components Nuxt 3 also provides meta components that you can use to accomplish the same task. While these components look similar to HTML tags, they are provided by Nuxt and have similar functionality. Nuxt 2 Nuxt 3 <script> export default { head () { return { title: 'My App', meta: [{ hid: 'description', name: 'description', content: 'My App Description' }] } } } </script> Make sure you use capital letters for these component names to distinguish them from native HTML elements (<Title> rather than <title>). You can place these components anywhere in your template for your page. Options API Nuxt 3 (Options API) <script> // if using options API `head` method you must use `defineNuxtComponent` export default defineNuxtComponent({ head (nuxtApp) { // `head` receives the nuxt app but cannot access the component instance return { meta: [{ name: 'description', content: 'This is my page description.' }] } } }) </script> Auto Imports Nuxt 3 adopts a minimal friction approach, meaning wherever possible components and composables are auto-imported. Plugins and Middleware Learn how to migrate from Nuxt 2 to Nuxt 3 plugins and middleware.
Migrate to Nuxt 3: Meta Tags
https://nuxt.com/docs/examples/advanced/config-extends
Examples Advanced Layers This example shows how to use the extends key in `nuxt.config.ts`. This example shows how to use the extends key in nuxt.config.ts to use the base/ directory as a base Nuxt application, and use its components, composables or config and override them if necessary. Read more in Docs > Getting Started > Layers. Loading Sandbox... Universal Router This example demonstrates Nuxt universal routing utilities without depending on `pages/` and `vue-router`. Error Handling This example shows how to handle errors in different contexts: pages, plugins, components and middleware.
Layers · Nuxt Examples
https://nuxt.com/docs/examples/features/auto-imports
Examples Features Auto Imports This example demonstrates the auto-imports feature in Nuxt. Example of the auto-imports feature in Nuxt with: Vue components in the components/ directory are auto-imported and can be used directly in your templates. Vue composables in the composables/ directory are auto-imported and can be used directly in your templates and JS/TS files. JS/TS variables and functions in the utils/ directory are auto-imported and can be used directly in your templates and JS/TS files. Read more in Docs > Guide > Directory Structure > Components. Read more in Docs > Guide > Directory Structure > Composables. Read more in Docs > Guide > Directory Structure > Utils. Loading Sandbox... Hello World A minimal Nuxt 3 application only requires the `app.vue` and `nuxt.config.js` files. Data Fetching This example demonstrates data fetching with Nuxt 3 using built-in composables and API routes.
Auto Imports · Nuxt Examples
https://nuxt.com/docs/examples/routing/middleware
Examples Routing Middleware This example shows how to add route middleware with the middleware/ directory or with a plugin, and how to use them globally or per page. Read more in Docs > Guide > Directory Structure > Middleware. Loading Sandbox... Layouts This example shows how to define default and custom layouts. Pages This example shows how to use the pages/ directory to create application routes.
Middleware · Nuxt Examples
https://nuxt.com/docs/api/commands/dev
Commands nuxi dev Source The dev command starts a development server with hot module replacement at http://localhost:3000 Terminal npx nuxi dev [rootDir] [--dotenv] [--log-level] [--clipboard] [--open, -o] [--no-clear] [--port, -p] [--host, -h] [--https] [--ssl-cert] [--ssl-key] The dev command starts a development server with hot module replacement at http://localhost:3000 Option Default Description rootDir . The root directory of the application to serve. --dotenv . Point to another .env file to load, relative to the root directory. --clipboard false Copy URL to clipboard. --open, -o false Open URL in browser. --no-clear false Does not clear the console after startup. --port, -p 3000 Port to listen. --host, -h localhost Hostname of the server. --https false Listen with https protocol with a self-signed certificate by default. --ssl-cert null Specify a certificate for https. --ssl-key null Specify the key for the https certificate. The port and host can also be set via NUXT_PORT, PORT, NUXT_HOST or HOST environment variables. Additionally to the above options, nuxi can pass options through to listhen, e.g. --no-qr to turn off the dev server QR code. You can find the list of listhen options in the unjs/listhen docs. This command sets process.env.NODE_ENV to development. If you are using a self-signed certificate in development, you will need to set NODE_TLS_REJECT_UNAUTHORIZED=0 in your environment. nuxi cleanup Remove common generated Nuxt files and caches. nuxi devtools The devtools command allows you to enable or disable Nuxt DevTools on a per-project basis.
nuxi dev · Nuxt Commands
https://nuxt.com/docs/api/kit/modules
Nuxt Kit Modules Source Nuxt Kit provides a set of utilities to help you create and use modules. You can use these utilities to create your own modules or to reuse existing modules. Modules are the building blocks of Nuxt. Kit provides a set of utilities to help you create and use modules. You can use these utilities to create your own modules or to reuse existing modules. For example, you can use the defineNuxtModule function to define a module and the installModule function to install a module programmatically. defineNuxtModule Define a Nuxt module, automatically merging defaults with user provided options, installing any hooks that are provided, and calling an optional setup function for full control. Type function defineNuxtModule<OptionsT extends ModuleOptions> (definition: ModuleDefinition<OptionsT> | NuxtModule<OptionsT>): NuxtModule<OptionsT> type ModuleOptions = Record<string, any> interface ModuleDefinition<T extends ModuleOptions = ModuleOptions> { meta?: ModuleMeta defaults?: T | ((nuxt: Nuxt) => T) schema?: T hooks?: Partial<NuxtHooks> setup?: (this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupReturn> } interface NuxtModule<T extends ModuleOptions = ModuleOptions> { (this: void, inlineOptions: T, nuxt: Nuxt): Awaitable<void | false | ModuleSetupReturn> getOptions?: (inlineOptions?: T, nuxt?: Nuxt) => Promise<T> getMeta?: () => Promise<ModuleMeta> } interface ModuleSetupReturn { timings?: { setup?: number [key: string]: number | undefined } } interface ModuleMeta { name?: string version?: string configKey?: string compatibility?: NuxtCompatibility [key: string]: unknown } Parameters definition Type: ModuleDefinition<T> | NuxtModule<T> Required: true A module definition object or a module function. meta (optional) Type: ModuleMeta Metadata of the module. It defines the module name, version, config key and compatibility. defaults (optional) Type: T | ((nuxt: Nuxt) => T) Default options for the module. If a function is provided, it will be called with the Nuxt instance as the first argument. schema (optional) Type: T Schema for the module options. If provided, options will be applied to the schema. hooks (optional) Type: Partial<NuxtHooks> Hooks to be installed for the module. If provided, the module will install the hooks. setup (optional) Type: (this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupReturn> Setup function for the module. If provided, the module will call the setup function. Examples // https://github.com/nuxt/starter/tree/module import { defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule' }, defaults: { test: 123 }, setup (options, nuxt) { nuxt.hook('modules:done', () => { console.log('My module is ready with current test option: ', options.test) }) } }) installModule Install specified Nuxt module programmatically. This is helpful when your module depends on other modules. You can pass the module options as an object to inlineOptions and they will be passed to the module's setup function. Type async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt) Parameters moduleToInstall Type: string | NuxtModule Required: true The module to install. Can be either a string with the module name or a module object itself. inlineOptions Type: any Default: {} An object with the module options to be passed to the module's setup function. nuxt Type: Nuxt Default: useNuxt() Nuxt instance. If not provided, it will be retrieved from the context via useNuxt() call. Examples import { defineNuxtModule, installModule } from '@nuxt/kit' export default defineNuxtModule({ async setup (options, nuxt) { // will install @nuxtjs/fontaine with Roboto font and Impact fallback await installModule('@nuxtjs/fontaine', { // module configuration fonts: [ { family: 'Roboto', fallbacks: ['Impact'], fallbackName: 'fallback-a', } ] }) } }) nuxi upgrade The upgrade command upgrades Nuxt 3 to the latest version. Programmatic Usage Nuxt Kit provides a set of utilities to help you work with Nuxt programmatically. These functions allow you to load Nuxt, build Nuxt, and load Nuxt configuration.
Modules · Nuxt Kit
https://nuxt.com/docs/guide/directory-structure/app
Guide Directory Structure app.vue The app.vue file is the main component of your Nuxt application. Minimal Usage With Nuxt 3, the pages/ directory is optional. If not present, Nuxt won't include vue-router dependency. This is useful when working on a landing page or an application that does not need routing. app.vue <template> <h1>Hello World!</h1> </template> Read and edit a live example in Docs > Examples > Hello World. Usage with Pages If you have a pages/ directory, to display the current page, use the <NuxtPage> component: app.vue <template> <div> <NuxtLayout> <NuxtPage/> </NuxtLayout> </div> </template> Since <NuxtPage> internally uses Vue's <Suspense> component, it cannot be set as a root element. Remember that app.vue acts as the main component of your Nuxt application. Anything you add to it (JS and CSS) will be global and included in every page. If you want to have the possibility to customize the structure around the page between pages, check out the layouts/ directory. app.config.ts Expose reactive configuration within your application with the App Config file. nuxt.config.ts Nuxt can be easily configured with a single nuxt.config file.
app.vue · Nuxt Directory Structure
https://nuxt.com/docs/community/roadmap
Community Roadmap Nuxt is constantly evolving, with new features and modules being added all the time. See our blog for the latest framework and ecosystem announcements. Status Reports Documentation Progress Rendering Optimizations: Today and Tomorrow Nuxt Image: Performance and Status Roadmap In roadmap below are some features we are planning or working on at the moment. Check Discussions and RFCs for more upcoming features and ideas. Milestone Expected date Notes Description SEO & PWA 2023 nuxt/nuxt#18395 Migrating from nuxt-community/pwa-module for built-in SEO utils and service worker support DevTools 2023 - Integrated and modular devtools experience for Nuxt Scripts 2023 nuxt/nuxt#22016 Easy 3rd party script management. Fonts 2023 nuxt/nuxt#22014 Allow developers to easily configure fonts in their Nuxt apps. Assets 2023 nuxt/nuxt#22012 Allow developers and modules to handle loading third-party assets. A11y 2023 nuxt/nuxt#23255 Accessibility hinting and utilities Translations - nuxt/translations#4 (request access) A collaborative project for a stable translation process for Nuxt 3 docs. Currently pending for ideas and documentation tooling support (content v2 with remote sources). Core Modules In addition to the Nuxt framework, there are modules that are vital for the ecosystem. Their status will be updated below. Module Status Nuxt Support Repository Description Auth Planned 3.x nuxt/auth to be announced Nuxt 3 support is planned after session support Image Active 2.x and 3.x nuxt/image Nuxt 3 support is in progress: nuxt/image#548 I18n Active 2.x and 3.x nuxt-modules/i18n See nuxt-modules/i18n#1287 for Nuxt 3 support Release Cycle Since January 2023, we've adopted a consistent release cycle for Nuxt 3, following semver. We aim for major framework releases every year, with an expectation of patch releases every week or so and minor releases every month or so. They should never contain breaking changes except within options clearly marked as experimental. Ongoing Support for Nuxt Going forward from v3, we commit to support each major version of Nuxt for a minimum of a year after the last release, and to providing an upgrade path for current users at that point. Current Packages The current active version of Nuxt is v3 which is available as nuxt on npm with the latest tag. Nuxt 2 is in maintenance mode and is available on npm with the 2x tag. It will reach End of Life (EOL) on December 31st, 2023 at the same time as Vue 2 does. Each active version has its own nightly releases which are generated automatically. For more about enabling the Nuxt 3 nightly release channel, see the nightly release channel docs. Release Initial release End Of Life Docs 4.x (scheduled) 2024 Q1 3.x (stable) 2022-11-16 TBA nuxt.com 2.x (maintenance) 2018-09-21 2023-12-31 v2.nuxt.com 1.x (unsupported) 2018-01-08 2019-09-21 Support Status Status Description Unsupported This version is not maintained any more and will not receive security patches Maintenance This version will only receive security patches Stable This version is being developed for and will receive security patches Development This version could be unstable Scheduled This version does not exist yet but is planned Framework Some specific points about contributions to the framework repository. Releases Discover the latest releases of Nuxt & Nuxt official modules.
Roadmap · Nuxt Community
https://nuxt.com/docs/guide/going-further/experimental-features
Guide Going Further Experimental Features Enable Nuxt experimental features to unlock new possibilities. The Nuxt experimental features can be enabled in the Nuxt configuration file. Internally, Nuxt uses @nuxt/schema to define these experimental features. You can refer to the API documentation or the source code for more information. Note that these features are experimental and could be removed or modified in the future. asyncContext Enable native async context to be accessible for nested composables in Nuxt and in Nitro. This opens the possibility to use composables inside async composables and reduce the chance to get the Nuxt instance is unavailable error. nuxt.config.ts export defineNuxtConfig({ experimental: { asyncContext: true } }) See full explanation on the GitHub pull-request. asyncEntry Enables generation of an async entry point for the Vue bundle, aiding module federation support. nuxt.config.ts export defineNuxtConfig({ experimental: { asyncEntry: true } }) externalVue Externalizes vue, @vue/* and vue-router when building. Enabled by default. nuxt.config.ts export defineNuxtConfig({ experimental: { externalVue: true } }) This feature will likely be removed in a near future. treeshakeClientOnly Tree shakes contents of client-only components from server bundle. Enabled by default. nuxt.config.ts export defineNuxtConfig({ experimental: { treeshakeClientOnly: true } }) emitRouteChunkError Emits app:chunkError hook when there is an error loading vite/webpack chunks. Default behavior is to perform a hard reload of the new route when a chunk fails to load. You can disable automatic handling by setting this to false, or handle chunk errors manually by setting it to manual. nuxt.config.ts export defineNuxtConfig({ experimental: { emitRouteChunkError: 'automatic' // or 'manual' or false } }) restoreState Allows Nuxt app state to be restored from sessionStorage when reloading the page after a chunk error or manual reloadNuxtApp() call. To avoid hydration errors, it will be applied only after the Vue app has been mounted, meaning there may be a flicker on initial load. Consider carefully before enabling this as it can cause unexpected behavior, and consider providing explicit keys to useState as auto-generated keys may not match across builds. nuxt.config.ts export defineNuxtConfig({ experimental: { restoreState: true } }) inlineRouteRules Define route rules at the page level using defineRouteRules. nuxt.config.ts export defineNuxtConfig({ experimental: { inlineRouteRules: true } }) Matching route rules will be created, based on the page's path. Read more in defineRouteRules utility. Read more in Docs > Guide > Concepts > Rendering #hybrid Rendering. inlineSSRStyles Inlines styles when rendering HTML. This is currently available only when using Vite. You can also pass a function that receives the path of a Vue component and returns a boolean indicating whether to inline the styles for that component. nuxt.config.ts export defineNuxtConfig({ experimental: { inlineSSRStyles: true // or a function to determine inlining } }) noScripts Disables rendering of Nuxt scripts and JS resource hints. Can also be configured granularly within routeRules. nuxt.config.ts export defineNuxtConfig({ experimental: { noScripts: true } }) renderJsonPayloads Allows rendering of JSON payloads with support for revivifying complex types. Enabled by default. nuxt.config.ts export defineNuxtConfig({ experimental: { renderJsonPayloads: true } }) noVueServer Disables Vue server renderer endpoint within Nitro. nuxt.config.ts export defineNuxtConfig({ experimental: { noVueServer: true } }) payloadExtraction Enables extraction of payloads of pages generated with nuxt generate. nuxt.config.ts export defineNuxtConfig({ experimental: { payloadExtraction: true } }) clientFallback Enables the experimental <NuxtClientFallback> component for rendering content on the client if there's an error in SSR. nuxt.config.ts export defineNuxtConfig({ experimental: { clientFallback: true } }) crossOriginPrefetch Enables cross-origin prefetch using the Speculation Rules API. nuxt.config.ts export defineNuxtConfig({ experimental: { crossOriginPrefetch: true } }) Read more about the Speculation Rules API. viewTransition Enables View Transition API integration with client-side router. nuxt.config.ts export defineNuxtConfig({ experimental: { viewTransition: true } }) Read and edit a live example in https://stackblitz.com/edit/nuxt-view-transitions?file=app.vue. Read more about the View Transition API. writeEarlyHints Enables writing of early hints when using node server. nuxt.config.ts export defineNuxtConfig({ experimental: { writeEarlyHints: true } }) componentIslands Enables experimental component islands support with <NuxtIsland> and .island.vue files. nuxt.config.ts export defineNuxtConfig({ experimental: { componentIslands: true // false or 'local+remote' } }) Read more in Docs > Guide > Directory Structure > Components #server Components. You can follow the server components roadmap on GitHub. configSchema Enables config schema support. Enabled by default. nuxt.config.ts export defineNuxtConfig({ experimental: { configSchema: true } }) polyfillVueUseHead Adds a compatibility layer for modules, plugins, or user code relying on the old @vueuse/head API. nuxt.config.ts export defineNuxtConfig({ experimental: { polyfillVueUseHead: false } }) respectNoSSRHeader Allow disabling Nuxt SSR responses by setting the x-nuxt-no-ssr header. nuxt.config.ts export defineNuxtConfig({ experimental: { respectNoSSRHeader: false } }) localLayerAliases Resolve ~, ~~, @ and @@ aliases located within layers with respect to their layer source and root directories. Enabled by default. nuxt.config.ts export defineNuxtConfig({ experimental: { localLayerAliases: true } }) typedPages Enable the new experimental typed router using unplugin-vue-router. nuxt.config.ts export defineNuxtConfig({ experimental: { typedPages: true } }) Out of the box, this will enable typed usage of navigateTo, <NuxtLink>, router.push() and more. You can even get typed params within a page by using const route = useRoute('route-name'). watcher Set an alternative watcher that will be used as the watching service for Nuxt. Nuxt uses chokidar-granular by default, which will ignore top-level directories (like node_modules and .git) that are excluded from watching. You can set this instead to parcel to use @parcel/watcher, which may improve performance in large projects or on Windows platforms. You can also set this to chokidar to watch all files in your source directory. nuxt.config.ts export defineNuxtConfig({ experimental: { watcher: 'chokidar-granular' // 'chokidar' or 'parcel' are also options } }) tsconfig.json Nuxt generates a .nuxt/tsconfig.json file with sensible defaults and your aliases. How Nuxt Works? Nuxt is a minimal but highly customizable framework to build web applications.
Experimental Features · Nuxt Advanced
https://nuxt.com/docs/api/nuxt-config
Nuxt Configuration Discover all the options you can use in your nuxt.config.ts file. This file is auto-generated from Nuxt source code. _build Type: boolean Default: false _cli Type: boolean Default: false _generate Type: boolean Default: false _installedModules Type: array _legacyGenerate Type: boolean Default: false _majorVersion Type: number Default: 3 _modules Type: array _nuxtConfigFile _nuxtConfigFiles Type: array _prepare Type: boolean Default: false _requiredModules _start Type: boolean Default: false alias Type: object Default { "~": "/<rootDir>", "@": "/<rootDir>", "~~": "/<rootDir>", "@@": "/<rootDir>", "assets": "/<rootDir>/assets", "public": "/<rootDir>/public" } analyzeDir Type: string Default: "/<rootDir>/.nuxt/analyze" app baseURL Type: string Default: "/" buildAssetsDir Type: string Default: "/_nuxt/" cdnURL Type: string Default: "" head Type: object Default { "meta": [ { "name": "viewport", "content": "width=device-width, initial-scale=1" }, { "charset": "utf-8" } ], "link": [], "style": [], "script": [], "noscript": [] } keepalive Type: boolean Default: false layoutTransition Type: boolean Default: false pageTransition Type: boolean Default: false rootId Type: string Default: "__nuxt" rootTag Type: string Default: "div" appConfig nuxt appDir Type: string Default: "" build analyze Type: object Default { "template": "treemap", "projectRoot": "/<rootDir>", "filename": "/<rootDir>/.nuxt/analyze/{name}.html" } templates Type: array transpile Type: array buildDir Type: string Default: "/<rootDir>/.nuxt" builder Type: string Default: "@nuxt/vite-builder" components Type: object Default { "dirs": [ { "path": "~/components/global", "global": true }, "~/components" ] } css Type: array debug Type: boolean Default: false dev Type: boolean Default: false devServer host https Type: boolean Default: false loadingTemplate Type: function port Type: number Default: 3000 url Type: string Default: "http://localhost:3000" devServerHandlers Type: array devtools dir assets Type: string Default: "assets" layouts Type: string Default: "layouts" middleware Type: string Default: "middleware" modules Type: string Default: "modules" pages Type: string Default: "pages" plugins Type: string Default: "plugins" public Type: string Default: "public" static Type: string Default: "public" experimental appManifest Type: boolean Default: true asyncContext Type: boolean Default: false asyncEntry Type: boolean Default: false clientFallback Type: boolean Default: false componentIslands Type: boolean Default: false configSchema Type: boolean Default: true crossOriginPrefetch Type: boolean Default: false defaults nuxtLink componentName Type: string Default: "NuxtLink" useAsyncData deep Type: boolean Default: true useFetch emitRouteChunkError Type: string Default: "automatic" externalVue Type: boolean Default: true headNext Type: boolean Default: false inlineRouteRules Type: boolean Default: false inlineSSRStyles Type: boolean Default: true localLayerAliases Type: boolean Default: true noScripts Type: boolean Default: false noVueServer Type: boolean Default: false payloadExtraction Type: boolean Default: true polyfillVueUseHead Type: boolean Default: false reactivityTransform Type: boolean Default: false renderJsonPayloads Type: boolean Default: true respectNoSSRHeader Type: boolean Default: false restoreState Type: boolean Default: false templateRouteInjection Type: boolean Default: true treeshakeClientOnly Type: boolean Default: true typedPages Type: boolean Default: false typescriptBundlerResolution Type: boolean Default: false viewTransition Type: boolean Default: false watcher Type: string Default: "chokidar-granular" writeEarlyHints Type: boolean Default: false extends Default: null extensions Type: array Default [ ".js", ".jsx", ".mjs", ".ts", ".tsx", ".vue" ] generate exclude Type: array routes Type: array hooks Default: null ignore Type: array Default [ "**/*.stories.{js,cts,mts,ts,jsx,tsx}", "**/*.{spec,test}.{js,cts,mts,ts,jsx,tsx}", "**/*.d.{cts,mts,ts}", "**/.{pnpm-store,vercel,netlify,output,git,cache,data}", ".nuxt/analyze", ".nuxt", "**/-*.*" ] ignoreOptions ignorePrefix Type: string Default: "-" imports dirs Type: array global Type: boolean Default: false logLevel Type: string Default: "info" modules Type: array modulesDir Type: array Default [ "/<rootDir>/node_modules", "/Users/daniel/code/nuxt.js/packages/schema/node_modules" ] nitro routeRules Type: object optimization asyncTransforms asyncFunctions Type: array Default [ "defineNuxtPlugin", "defineNuxtRouteMiddleware" ] objectDefinitions defineNuxtComponent Type: array Default [ "asyncData", "setup" ] defineNuxtPlugin Type: array Default [ "setup" ] definePageMeta Type: array Default [ "middleware", "validate" ] keyedComposables Type: array Default [ { "name": "defineNuxtComponent", "argumentLength": 2 }, { "name": "useState", "argumentLength": 2 }, { "name": "useFetch", "argumentLength": 3 }, { "name": "useAsyncData", "argumentLength": 3 }, { "name": "useLazyAsyncData", "argumentLength": 3 }, { "name": "useLazyFetch", "argumentLength": 3 } ] treeShake composables client Type: object Default { "vue": [ "onServerPrefetch", "onRenderTracked", "onRenderTriggered" ], "#app": [ "definePayloadReducer", "definePageMeta" ] } server Type: object Default { "vue": [ "onBeforeMount", "onMounted", "onBeforeUpdate", "onRenderTracked", "onRenderTriggered", "onActivated", "onDeactivated", "onBeforeUnmount" ], "#app": [ "definePayloadReviver", "definePageMeta" ] } pages Type: boolean plugins Type: array postcss plugins autoprefixer cssnano Type: object rootDir Type: string Default: "/<rootDir>" routeRules router options hashMode Type: boolean Default: false scrollBehaviorType Type: string Default: "auto" runtimeConfig Type: object Default { "public": {}, "app": { "baseURL": "/", "buildAssetsDir": "/_nuxt/", "cdnURL": "" } } serverDir Type: string Default: "/<rootDir>/server" serverHandlers Type: array sourcemap Type: object Default { "server": true, "client": false } spaLoadingTemplate Default: null srcDir Type: string Default: "/<rootDir>" ssr Type: boolean Default: true telemetry test Type: boolean Default: false theme Type: string Default: null typescript builder Default: null includeWorkspace Type: boolean Default: false shim Type: boolean Default: true strict Type: boolean Default: true tsConfig Type: object Default { "compilerOptions": {} } typeCheck Type: boolean Default: false vite build assetsDir Type: string Default: "_nuxt/" emptyOutDir Type: boolean Default: false clearScreen Type: boolean Default: true define Type: object Default { "process.dev": false, "import.meta.dev": false, "process.test": false, "import.meta.test": false } esbuild jsxFactory Type: string Default: "h" jsxFragment Type: string Default: "Fragment" tsconfigRaw Type: string Default: "{}" mode Type: string Default: "production" optimizeDeps exclude Type: array Default [ "vue-demi" ] publicDir Type: string Default: "/<rootDir>/public" resolve extensions Type: array Default [ ".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue" ] root Type: string Default: "/<rootDir>" server fs allow Type: array Default [ "/<rootDir>/.nuxt", "/<rootDir>", "/<rootDir>", "/<rootDir>", "/<rootDir>/node_modules", "/Users/daniel/code/nuxt.js/packages/schema/node_modules" ] vue isProduction Type: boolean Default: true script defineModel Type: boolean Default: false propsDestructure Type: boolean Default: false template compilerOptions Type: object vueJsx Type: object vue compilerOptions defineModel Type: boolean Default: false propsDestructure Type: boolean Default: false runtimeCompiler Type: boolean Default: false watch Type: array watchers chokidar ignoreInitial Type: boolean Default: true rewatchOnRawEvents webpack aggregateTimeout Type: number Default: 1000 webpack aggressiveCodeRemoval Type: boolean Default: false analyze Type: object Default { "template": "treemap", "projectRoot": "/<rootDir>", "filename": "/<rootDir>/.nuxt/analyze/{name}.html" } cssSourceMap Type: boolean Default: false devMiddleware stats Type: string Default: "none" experiments extractCSS Type: boolean Default: true filenames app Type: function chunk Type: function css Type: function font Type: function img Type: function video Type: function friendlyErrors Type: boolean Default: true hotMiddleware loaders css esModule Type: boolean Default: false importLoaders Type: number Default: 0 url filter Type: function cssModules esModule Type: boolean Default: false importLoaders Type: number Default: 0 modules localIdentName Type: string Default: "[local]_[hash:base64:5]" url filter Type: function esbuild file esModule Type: boolean Default: false fontUrl esModule Type: boolean Default: false limit Type: number Default: 1000 imgUrl esModule Type: boolean Default: false limit Type: number Default: 1000 less Default { "sourceMap": false } pugPlain sass sassOptions indentedSyntax Type: boolean Default: true scss Default { "sourceMap": false } stylus Default { "sourceMap": false } vue compilerOptions Type: object defineModel Type: boolean Default: false propsDestructure Type: boolean Default: false transformAssetUrls embed Type: string Default: "src" object Type: string Default: "src" source Type: string Default: "src" video Type: string Default: "src" vueStyle Default { "sourceMap": false } optimization minimize Type: boolean Default: true minimizer runtimeChunk Type: string Default: "single" splitChunks automaticNameDelimiter Type: string Default: "/" cacheGroups chunks Type: string Default: "all" optimizeCSS Type: boolean Default: false plugins Type: array postcss postcssOptions config plugins Type: object Default { "autoprefixer": {}, "cssnano": {} } profile Type: boolean Default: false serverURLPolyfill Type: string Default: "url" warningIgnoreFilters Type: array workspaceDir Type: string Default: "/<rootDir>" Import meta Understand where your code is running using `import.meta`. Getting Help We're a friendly community of developers and we'd love to help.
Nuxt Configuration